I have a simple question, which will help me to understand a lot ( I hope!)
Well, I have this code:
// Getting contacts Count
public int getContactsCount() {
helper = new DBHelper(CheckTable.this);
SQLiteDatabase db = helper.getReadableDatabase();
String countQuery = "SELECT * FROM " + Market.TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
How may I display this number?!
I thank you in advance...
This method is going to return you an int. Hence you have to declare it in your class. Assuming that you want to display this number in the same class you can simply follow this:
public class Example{
// Getting contacts Count
public int getContactsCount() {
helper = new DBHelper(CheckTable.this);
SQLiteDatabase db = helper.getReadableDatabase();
String countQuery = "SELECT * FROM " + Market.TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public static void main(String[] args) { //main method
int a= getContactsCount(); //calling the method
System.out.println(a); //displaying the integer
}
}
To display the value in a textview:
public class MyActvitiy Extends Activity{
public void onCreate(Bundle b){
super.onCreate(b);
//sets the view to the xml file that contains the textview
setContentView(R.layout.myActvityLayout);
//inflates textview from xml
TextView tv_contactCount = findViewById(R.id.tv_contactCount);
//creates a new example object
Example e = new Example();
//sets the textview to equal the count
tv_contactCount.setText(e.getContactsCount());
}
}
However, you may want to go over Android fundamentals to ensure you get a comprehensive understanding.
Related
I want to make a to-do list app, and I wanted to delete the item in the list by tapping the checkbox.
I tried to make a "deleteTask"(as you see in the code) method in the database class. Also, you can see the "populateListView"
method, it provides data from the database into listview, I use it to refresh after each time a task got deleted from the database.
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 , new String[]{task});
}
public void populateListView() {
try {
mDataBaseHelper = new DataBaseHelper(MainActivity.this);
data = mDataBaseHelper.getData();
mArrayList = new ArrayList<>();
if (data.getCount() != 0) {
while (data.moveToNext()) {
mArrayList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter(MainActivity.this, R.layout.list_items, R.id.checkBox, mArrayList);
list = (ListView) findViewById(R.id.myListId);
list.setAdapter(listAdapter);
}
mDataBaseHelper.close();
} else {
toastMessage("the Database is empty");
}
}catch(Exception e){
Log.e(TAG, "populateListView: error"+e.getStackTrace() );
}
}
when the application gets started, I tapped the item that I want to delete, but I see that the items start to be deleted by order from above!
one by one each time I tapped any checkbox.
You want :-
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 + "=?" , new String[]{task});
}
If you weren't trapping the error by using the try/catch using db.delete(TABLE_NAME, COL2 , new String[]{task}); you would get an exception along the lines of :-
java.lang.IllegalArgumentException: Too many bind arguments. 1 arguments were provided but the statement needs 0 arguments.
However
Assuming that the issue with deleting rows sequentially rather than according to the checked item(s), is likely due to the handling of the checked items. However, as the code for this is not provided it would only be guess work to know where in the code you are going wrong.
One thing is that you do not want to be creating a new listadapter instance every time you populate the ListView.
As a hint to handling a ListView, but deleting an item when it is long-clicked based upon the COL2 value, perhaps consider the following which has been based upon your code (but deletes according to long clicking an item) :-
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this); //<<<<<<<<<< NOTE 1
list = (ListView) this.findViewById(R.id.myListId); //<<<<<<<<<< NOTE 1
data = mDataBaseHelper.getData(); //<<<<<<<<<< get the data to be listed
if (listadapter == null) { //<<<<<<<<<< Only need to instantiate one adapter when it has not bee instantiated
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data); // for convenience using a stock layout
list.setAdapter(listadapter);
//<<<<<<<<<<< add the onItemLongClick listener
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mDataBaseHelper.deleteTaskByCol2(data.get(position)); //<<<<<<<<<< gets the value of the item according to it's position in the list
populateLisView(); //<<<<<<<<<< as the item has been deleted then refresh the Listview
return true; // flag the event as having been handled.
}
});
//<<<<<<<<<<< If the Adapter has been instantiated then refresh the ListView's data
} else {
listadapter.clear(); // Clear the data from the adapter
listadapter.addAll(data); // add the new changed data to the adapter
listadapter.notifyDataSetChanged(); // tell the adapter that the data has changed
}
}
NOTE 1
you would typically instantiate these variables once.
Check the comments
You may wish to edit your question to include how you are handling the check events.
The Full Working Example
DatabaseHelper.java
Note this may differ from yours a little
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COL1 = "col1";
public static final String COL2 = "col2";
SQLiteDatabase db;
private static final String CRT_MYTABLE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" +
COL1 + " TEXT, " +
COL2 + " TEXT" +
")";
public DataBaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRT_MYTABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addMytableRow(String col1, String col2) {
ContentValues cv = new ContentValues();
cv.put(COL1,col1);
cv.put(COL2,col2);
return db.insert(TABLE_NAME,null,cv);
}
public ArrayList<String> getData() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL2)));
}
csr.close();
return rv;
}
public void deleteTaskByCol2(String task) {
db.delete(TABLE_NAME,COL2 + "=?",new String[]{task});
}
}
MainActivity.java
i.e. an example activity that is based upon your code, but according to the above :-
public class MainActivity extends AppCompatActivity {
DataBaseHelper mDataBaseHelper;
ArrayList<String> data;
ListView list;
ArrayAdapter<String> listadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addSomeTestData();
populateLisView();
}
private void example001() {
}
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this);
list = (ListView) this.findViewById(R.id.myListId);
data = mDataBaseHelper.getData();
if (listadapter == null) {
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data);
list.setAdapter(listadapter);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//mDataBaseHelper.deleteTaskWrong(data.get(position)); // ooops
mDataBaseHelper.deleteTaskByCol2(data.get(position));
populateLisView();
return true;
}
});
} else {
listadapter.clear();
listadapter.addAll(data);
listadapter.notifyDataSetChanged();
}
}
private void addSomeTestData() {
if (mDataBaseHelper == null) {
mDataBaseHelper = new DataBaseHelper(this);
}
if (DatabaseUtils.queryNumEntries(mDataBaseHelper.getWritableDatabase(),DataBaseHelper.TABLE_NAME) > 0) return;
mDataBaseHelper.addMytableRow("Test1","Test1");
mDataBaseHelper.addMytableRow("Test2","Test2");
mDataBaseHelper.addMytableRow("Test3","Test3");
mDataBaseHelper.addMytableRow("Test4","Test4");
}
}
Note AddSomeTestData adds some data for testing/demonstration.
Result
When first run :-
After LongClicking Test 2
i.e. the long clicked item has been removed (from the list and the database) and the list refreshed.
Try to replace
db.delete(TABLE_NAME, COL2 , new String[]{task});
By
db.delete(TABLE_NAME, COL2 + " = ?" , new String[]{task});
I am setting a new activity named Dispatch Report, which has two Spinners: CustomerSpinner and LotSpinner.
LotSpinner shows all Lots in Dispatch Table instead of showing only those Lots which are related to the Customer selected in the first Spinner.
I have fetched CustomerSpinner Value from Dispatch Table. In LotSpinner also fetched Lot numbers from Dispatch Table, but not Filtered according to customer selection.
DispatchReportActivity.Java
// Fetching customer from dispatch table
private void loadCustomerNameDispatch() {
DatabaseHelper db = new DatabaseHelper( getApplicationContext() );
List<String> lables1 = db.getFirmNAmeMoveStock();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables1);
dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinCustomer.setAdapter(dataAdapter);
spinCustomer.setOnItemSelectedListener(this);
}
// Fetching lot from dispatch table
private void loadLotbyCustomerDispatch() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getLotbyCustomer();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinLotbyCustomer.setAdapter(dataAdapter);
}
DATABASEHELPER.Java
//Get firm name in Dispatch Stock Report screen
public List < String > getFirmNAmeMoveStock() {
List < String > labels = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_Inventory;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(3));
Set < String > set = new HashSet < >(labels);
labels.clear();
labels.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels;
}
// Method to get Lot No. in Dispatch Stock Report Activity
public List < String > getLotbyCustomer() {
List < String > labels1 = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_StockDispatch;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels1.add(cursor.getString(4));
Set < String > set = new HashSet < >(labels1);
labels1.clear();
labels1.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels1;
}
There will be multiple customers, and each customer could have multiple Lots, so I want the second spinner to show only those Lots which are relevant to the customer selected in the first Spinner.
I'd suggest utilising Cursor's and Cursor adapters which can make matter simpler as :-
there is no need for intermediate arrays (one of your issues is that String arrays do not provide sufficient information)
CursorAdapters are designed to handle id (albiet a requirement that these exists in the Cursor with the column name _id (see the use of BaseColumns._ID below)).
The following is a basic example of related spinners based loosely upon your requirements.
First the DatbaseHelper DatabaseHelper.java
Two tables are defined/created Customers and Lots, methods to add data for each exist as do methods to extract a list from each of the tables. The lots extracted are based upon the customer to which they reference/belong to/associate with.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TBL_CUSTOMER = "customer";
public static final String TBL_LOT = "lot";
public static final String COL_CUSTOMER_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_CUSTOMER_NAME = "customer_name";
public static final String COL_LOT_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_LOT_NAME = "lot_name";
public static final String COL_LOT_CUSTOMERREFERENCE = "customer_refererence";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase(); //<<<<<<<<<< get the database connection (force create when constructing helper instance)
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_customer_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID + " INTEGER PRIMARY KEY, " +
COL_CUSTOMER_NAME + " TEXT UNIQUE " +
")";
String crt_lot_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_LOT + "(" +
COL_LOT_ID + " INTEGER PRIMARY KEY, " +
COL_LOT_NAME + " TEXT, " +
COL_LOT_CUSTOMERREFERENCE + " INTEGER " +
/*?????????? OPTIONAL IF FOREIGN KEYS ARE TURNED ON
"REFERENCES " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID +
")" +
*/
")";
db.execSQL(crt_customer_table_sql);
db.execSQL(crt_lot_table_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addCustomer(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_CUSTOMER_NAME,name);
return mDB.insert(TBL_CUSTOMER,null,cv);
}
public long addLot(String name, long customer_reference) {
ContentValues cv = new ContentValues();
cv.put(COL_LOT_NAME,name);
cv.put(COL_LOT_CUSTOMERREFERENCE,customer_reference);
return mDB.insert(TBL_LOT,name,cv);
}
public Cursor getCustomers() {
return mDB.query(TBL_CUSTOMER,null,null,null,null,null,COL_CUSTOMER_NAME);
}
public Cursor getLotsPerCustomer(long customer_id) {
String whereclause = COL_LOT_CUSTOMERREFERENCE + "=?";
String[] whereargs = new String[]{String.valueOf(customer_id)};
return mDB.query(TBL_LOT,null,whereclause,whereargs,null,null,COL_LOT_NAME);
}
}
Note the above is pretty straight-forward. However, it would obviously need to be adapted to suit you App.
The second code is the activity that utilises the above and incorporates the 2 linked/related spinners where the selectable Lots are as per those lots associated with the currently selected customer.
The layout used for the activity is very basic, it just has two spinners. The spiners use the stock Simple_List_Item_2 layout (2 has been used to allow the all important ID's to be viewed (typically the user would not be shown the ID's)).
In short whenever a selection is made in the Customer spinner the Lot spinner is managed (setup or refreshed) based upon the customer id which is used to select the related/reference lots.
public class MainActivity extends AppCompatActivity {
Context mContext;
DatabaseHelper mDBHlpr;
SimpleCursorAdapter mCustomerSCA, mLotSCA;
Spinner mCustomerList, mLotList;
Cursor mCustomers, mLots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mDBHlpr = new DatabaseHelper(this);
mCustomerList = this.findViewById(R.id.customer_list);
mLotList = this.findViewById(R.id.lot_list);
addTestingDataIfNoData(); //Go and add some testing data if there is none
manageCustomerSpinner();
}
private void manageCustomerSpinner() {
mCustomers = mDBHlpr.getCustomers();
if (mCustomerSCA == null) {
mCustomerSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mCustomers,
new String[]{
DatabaseHelper.COL_CUSTOMER_NAME,
DatabaseHelper.COL_CUSTOMER_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mCustomerList.setAdapter(mCustomerSCA);
mCustomerList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageLotSpinner(id); //<<<<<<<<<< WHENEVER CUSTOMER IS SELECTED THE LOT SPINNER IS MANAGED >>>>>>>>>>
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mCustomerSCA.swapCursor(mCustomers);
}
}
private void manageLotSpinner(long id) {
mLots = mDBHlpr.getLotsPerCustomer(id);
if (mLotSCA == null) {
mLotSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mLots,
new String[]{
DatabaseHelper.COL_LOT_NAME,
DatabaseHelper.COL_LOT_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mLotList.setAdapter(mLotSCA);
} else {
mLotSCA.swapCursor(mLots);
}
}
private void addTestingDataIfNoData() {
if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TBL_CUSTOMER) < 1) {
mDBHlpr.addCustomer("Fred");
mDBHlpr.addCustomer("Mary");
mDBHlpr.addCustomer("Sue");
mDBHlpr.addCustomer("Alan");
mDBHlpr.addLot("Lot001",2); // Lot for mary
mDBHlpr.addLot("Lot002",1); // Lot for fred
mDBHlpr.addLot("Lot003",4); // Lot for ala
mDBHlpr.addLot("Lot004",3); // Lot for sue
mDBHlpr.addLot("Lot005",3); // Lot for sue
mDBHlpr.addLot("Lot006",3); // Lot for use
mDBHlpr.addLot("Lot007",2); // Lot for mary
mDBHlpr.addLot("Lot008",2); // Lot for mary
mDBHlpr.addLot("Lot009",2); // Lot for mary
mDBHlpr.addLot("Lot0010",2); // Lot for mary
mDBHlpr.addLot("Lot0020",1); // Lot for Fred
mDBHlpr.addLot("Lot00130",4); // Lot for Alan
mDBHlpr.addLot("Lot00130",3); // Lot for Sue
}
}
}
Result Example
Initial
Alan is initial selection due to sort order
After Selecting Mary
Note Lot names, as used, are not really suited to sorting
So my app is a QR Code scanner. Currently it will read a QR code and display it back to user. I want to get it to also save this result to a database and then proceed to read back from it. Currently it does neither of the last two and I'm struggling to figure out which is causing the issue - either saving to the database or reading back from the database.
My Database code is this:
public class Database {
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"codeid INTEGER PRIMARY KEY AUTOINCREMENT, " +
"code TEXT NOT NULL);";
public Database(Context ctx) {
this.dbContext = ctx;
}
public Database open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put("codes", code);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public ArrayList<String[]> fetchUser(String code) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"codeid", "code",
}, "code LIKE '%" + code + "%'", null,
null, null, null);
int codeNameColumn = mCursor.getColumnIndex("code");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(codeNameColumn);
pointer++;
} while (mCursor.moveToNext());
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "codeid", "codes" }, null, null, null, null, "codeid");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0);
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
And my main java code is this.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button Scan;
private ArrayList<String[]> viewall;
private TextView QR_output;
private IntentIntegrator ScanCode;
private ListView lv;
private ArrayList Search = new ArrayList();
ArrayList<String[]> searchResult;
Database dbh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this caused an error on earlier APKs which made the app switch from 17 to 27
setContentView(R.layout.activity_main);
// Defines the Scan button
Scan = findViewById(R.id.Scan);
// defines the output for text
QR_output = findViewById(R.id.QR_Output);
// looks for the user clicking "Scan"
Scan.setOnClickListener(this);
ScanCode = new IntentIntegrator(this);
// Means the scan button will actually do something
Scan.setOnClickListener(this);
lv = findViewById(R.id.list);
dbh = new Database(this);
dbh.open();
}
public void displayAll(View v){
Search.clear();
viewall = dbh.selectAll();
String surname = "", forename = "";
for (int count = 0 ; count < viewall.size() ; count++) {
code = viewall.get(count)[1];
Search.add(surname + ", " + forename);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
Search);
lv.setAdapter(arrayAdapter);
}
// will scan the qr code and reveal its secrets
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
// if an empty QR code gets scanned it returns a message to the user
if (result.getContents() == null) {
Toast.makeText(this, "This QR code is empty.", Toast.LENGTH_LONG).show();
} else try {
// converts the data so it can be displayed
JSONObject obj = new JSONObject(result.getContents());
// this line is busted and does nothing
QR_output.setText(obj.getString("result"));
} catch (JSONException e) {
e.printStackTrace();
String codes = result.getContents();
boolean success = false;
success = dbh.createUser(codes);
// outputs the data to a toast
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onClick(View view) {
// causes the magic to happen (It initiates the scan)
ScanCode.initiateScan();
}
}
Your issue could well be with the line initialValues.put("codes", code); as according to your table definition there is no column called codes, rather the column name appears to be code
As such using initialValues.put("code", code); may well resolve the issue.
Addititional
It is strongly recommended that you define and subsequently use constants throughout your code for all named
items (tables, columns, views trigger etc) and thus the value will always be identical.
e.g.
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
public static final String COLUMN_CODEID = "codeid"; //<<<<<<<<< example note making public allows the variable to be used elsewhere
public static final String COLUMN_CODE = "code"; //<<<<<<<<<< another example
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_CODEID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //<<<<<<<<<<
COLUMN_CODE + " TEXT NOT NULL);"; //<<<<<<<<<<
........ other code omitted for brevity
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_CODE, code); //<<<<<<<<<< CONSTANT USED
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
You would also likely encounter fewer issues by not using hard coded column offsets when extracting data from Cursor by rather using the Cursor getColumnIndex method to provide the offset.
e.g. instead of :-
results.get(counter)[0] = cursor.getString(0);
it would be better to use :-
results.get(counter)[0] = cursor.getString(cursor.getColumnIndex(COLUMN_CODEID));
I'm trying to get integer values, to be displayed in a listview from SQLlite using cursors but it shows the following error:
java.lang.IllegalStateException: Couldn't read row 0, col 4 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Here are my code
MyItems.java:
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
ArrayList<SalesItemInformationLV> items = new ArrayList<SalesItemInformationLV>();
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor != null && myCursor.getCount() > 0)
{
myCursor.moveToFirst();
do {
contactIdList.add(myCursor.getInt(db.COLUMN_KEY_ID));
items.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), myCursor.getInt(db.COLUMN_QTYSOLD_ID)));
} while (myCursor.moveToNext());
}
db.close();
return items;
}
MyDbAdapter.java:
private SQLiteDatabase _db;
private final Context context;
public static final String KEY_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String ENTRY_NAME = "entry_name";
public static final int COLUMN_NAME_ID = 1;
public static final String ENTRY_QTYSOLD = "entry_qtysold";
public static final int COLUMN_QTYSOLD_ID = 4;
private MyDBOpenHelper dbHelper;
//private MyDBOpenHelper dbHelper2;
public MyDbAdapter(Context _context)
{
this.context = _context;
//step 16 - create MyDBOpenHelper object
//constructor
dbHelper = new MyDBOpenHelper(context, DATABASE_NAMEA, null, DATABASE_VERSION);
//constructor
//dbHelper2 = new MyDBOpenHelper(context, DATABASE_NAME2, null, DATABASE_VERSION);
}
public Cursor retrieveAllEntriesCursor() {
//step 21 - retrieve all records from table
Cursor c = null;
try {
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);
}
catch (SQLiteException e)
{
Log.w(MYDBADAPTER_LOG_CAT, "Retrieve fail!");
}
return c;
}
I suspect the error comes from MyItems.java, but I'm having a hard time figuring out what's the error.
Seems like you are fetching only 2 columns(KEY_ID, ENTRY_NAME) from database and while reading you are expecting 3 columns.
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);
You are trying to get value from column 4, which is throuing an error.
public static final int COLUMN_QTYSOLD_ID = 4;
Use this method in your databasehelper class
public Cursor getalldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery(" select * from " + TABLE_Name, null);
return res;
}
**and call this method where you want to get your data from database table **
public void getdata(){
Cursor res = db.getstafdata(); //db id an object of database helper //class
if (res.getCount() == 0) {
Toast.makeText(getApplicationContext(),
"no data", Toast.LENGTH_LONG).show();
} else {
StringBuffer stbuff = new StringBuffer();
while (res.moveToNext()) {
detail.add(new doctor_details(res.getString(1),res.getString(2),res.getString(3)));
}
}
}
I cannot get the values of the four variables from the private Oncreate method to the public Intent method.
Below class creates a Pie Chart. Now i'm trying to fill this array with data from my SQlite database. int[] values = {dimensionPhysical, dimensionMental, dimensionSocial, dimensionSpirituality};
The database is openend in the oncreate method and I run 4 times the getcount query below.
public int getCount(String rowId) {
Cursor C = db.rawQuery("select count {*} from mainTable where " + KEY_DIMENSION + " = " + rowId, null);
return C.getCount();
}
Somehow I cannot get the values of the four variables from the private onCreate method to the public Intent method. The piechart is based on the intitial values of 1.
public class Balance extends Activity {
static DBAdapter myDb;
public int dimensionPhysical= 1;
public int dimensionMental= 1;
public int dimensionSocial= 1;
public int dimensionSpirituality= 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
openDB();
dimensionPhysical = myDb.getCount("Physical");
dimensionMental = myDb.getCount("Mental");
dimensionSocial = myDb.getCount("Social");
dimensionSpirituality = myDb.getCount("Spiritual");
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_ClearAll(View v) {
myDb.deleteAll();
}
public Intent getIntent(Context context) {
int[] values = {dimensionPhysical, dimensionMental, dimensionSocial, dimensionSpirituality};
CategorySeries series = new CategorySeries("Pie Graph");
int k = 0;
for (int value : values) {
series.add("Section " + ++k, value);
}
int[] colors = new int[]{Color.rgb(144, 238, 144), Color.rgb(173,216,230), Color.rgb(255,204,153), Color.rgb(240,204,153)};
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
renderer.setChartTitle("Pie Chart Demo");
renderer.setChartTitleTextSize(7);
renderer.setZoomButtonsVisible(true);
Intent intent = ChartFactory.getPieChartIntent(context, series, renderer, "Pie");
return intent;
}
}
I hope someone here knows how to fix this problem.
Try wrapping KEY_DIMENSION in single quotes (I guess it's a string):
Cursor C = db.rawQuery("select count {*} from mainTable where " + KEY_DIMENSION + " = '" + rowId + "'", null);
In any case, learn to use logcat and even debugger.