I want to have a method in the class GolferDBManager return an array of objects that I am constructing from an SQLLite db. I am getting a Source Not Found error in the method when I try to build the array.
public Golfer[] retrieveGolfers(){
String[] columns = new String[]{"golfer_name", "golfer_init", "usga_index"};
Cursor cursor = db.query(true, DB_TABLE, columns, null, null, null, null, null, null, null);
cursor.moveToFirst();
int i = 0;
while (cursor.isAfterLast() == false) {
Golfer tGolfer = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
lGolfers[i] = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return lGolfers;
}
lGolfers is defined above in the class definitions as:
public class GolferDBManager {
public static final String DB_NAME = "golfgames";
public static final String DB_TABLE = "golfers";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (index INTEGER PRIMARY KEY, golfer_name TEXT, golfer_init TEXT, usga_index DOUBLE);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
private Golfer lGolfers[];
The
Golfer tGolfer = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
line works fine. I added it for debug purposes. The next line generates the Source Not Found error. I know the constructor for the class Golfer is there because I just used in the previous line.
Here is the code that calls all of this:
public class ReadGolfers extends Activity {
public Golfer Golfers[];
private GolferDBManager mydManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_golfers);
mydManager = new GolferDBManager(this);
mydManager.openReadable();
Golfers = mydManager.retrieveGolfers();
mydManager.retrieveGolfers();
mydManager.close();
}
}
Can anyone help me understand why this isn't working?
Thanks.
As an afterthought, I changed the method to have the object array passed to it as follows:
public void retrieveGolfers(Golfer lgolfers[]){
String[] columns = new String[]{"golfer_name", "golfer_init", "usga_index"};
Cursor cursor = db.query(true, DB_TABLE, columns, null, null, null, null, null, null, null);
cursor.moveToFirst();
int i = 0;
while (cursor.isAfterLast() == false) {
lgolfers[i] = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
Still no joy.
Actually this whole line is wrong:
private Golfer lGolfers[];
It should be:
private Golfer[] lGolfers;
And initialized with:
lGolfers = new Golfer[100];
(or whatever size you wanted)
Much better is to use an ArrayList:
private ArrayList<Golfer> lGolfers = new ArrayList<Golfer>();
Related
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 want to save DatabaseTableDay to my SQLite in anndroid applicatin but something gones wrong.
My DatabaseDAODay is:
public class DatabaseDAODay {
public static final String TAG = "DaysDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DatabaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = { DatabaseHelper.COLUMN_DAY_ID,
DatabaseHelper.COLUMN_DAY_NAME, DatabaseHelper.COLUMN_DAY_WEIGHT};
public DatabaseDAODay(Context context) {
this.mContext = context;
mDbHelper = new DatabaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public DatabaseTableDay createDay(String name, float weight, Long id) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_DAY_NAME, name);
values.put(DatabaseHelper.COLUMN_DAY_WEIGHT, weight);
long insertId = id;
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
DatabaseHelper.COLUMN_DAY_ID + " = " + insertId, null, null,
null, null);
DatabaseTableDay newDay = new DatabaseTableDay();
if(cursor != null && cursor.moveToFirst()){
newDay = cursorToDay(cursor);
cursor.close();
Toast.makeText(mContext,"im here",Toast.LENGTH_LONG).show();
}
return newDay;
}
public void deleteDay(DatabaseTableDay databaseTableDay) {
long id = databaseTableDay.getId();
// delete all employees of this company
DatabaseDAOActivity databaseDAOActivity = new DatabaseDAOActivity(mContext);
List<DatabaseTableActivity> databaseTableActivities = databaseDAOActivity.getActivitiesOfDay(id);
if (databaseTableActivities != null && !databaseTableActivities.isEmpty()) {
for (DatabaseTableActivity e : databaseTableActivities) {
databaseDAOActivity.deleteActivity(e);
}
}
System.out.println("the deleted day has the id: " + id);
mDatabase.delete(DatabaseHelper.TABLE_DAYS, DatabaseHelper.COLUMN_DAY_ID
+ " = " + id, null);
}
public List<DatabaseTableDay> getAllDays() {
List<DatabaseTableDay> listDays = new ArrayList<DatabaseTableDay>();
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
DatabaseTableDay day = cursorToDay(cursor);
listDays.add(day);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listDays;
}
public DatabaseTableDay getDayById(long id) {
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS, mAllColumns,
DatabaseHelper.COLUMN_DAY_ID + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
DatabaseTableDay databaseTableDay = cursorToDay(cursor);
return databaseTableDay;
}
protected DatabaseTableDay cursorToDay(Cursor cursor) {
DatabaseTableDay databaseTableDay = new DatabaseTableDay();
databaseTableDay.setId(cursor.getLong(0));
databaseTableDay.setName(cursor.getString(1));
databaseTableDay.setWeight(cursor.getLong(2));
return databaseTableDay;
}
}
and I try to save it by:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseTableDay databaseTableDay = databaseDAODay.createDay(
editText.getText().toString(), 100f, new Long(myId));
List<DatabaseTableDay> list = databaseDAODay.getAllDays();
}
});
but list is empty anyway.
Probably the problem is createDay() method in DatabaseDAODay because if condition is always null and application doesn' run cursorToDay() method.
I had problem without condition and if there was only cursot.moveToFirst() and then cursorToDay() there was NullPoinerException - because coursor was null. I followed this and put condition !=null but actually nothing happens and List is always empty...
How should I solve my problem?
You are right about the problem being createDay(): instead of inserting a new day by using insert() you try to read from the database by using query()
Change your method like this:
public DatabaseTableDay createDay(String name, float weight, Long id) {
DatabaseTableDay dayToReturn;
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_DAY_NAME, name);
values.put(DatabaseHelper.COLUMN_DAY_WEIGHT, weight);
values.put(DatabaseHelper.COLUMN_DAY_ID, id);
long resID = mDatabase.insert(DatabaseHelper.TABLE_DAYS, null, values);
if (resID == -1)
{
// something went wrong, do error handling here
dayToReturn = null;
}
else
{
// no error: resID is "the row ID of the newly inserted row"
// you only need this info if you are using autoincrement
// not if you set the ID yourself
// all right, this will work -
// but somehow it hurts a little to retrieve an entry I just added.
// I'd like much more to simply use a constructor with all the values
// and create a new DatabaseTableDay instance
dayToReturn = getDayById(id);
}
return dayToReturn;
}
See also this link to documentation for SQLiteDatabase insert()
I want to display images from column 'images' in 'penyakit' table from sqlite database. That image display through TabGambar.java.
My friend told me than I can put address of image in database and save that image in drawable. But I don't understand how it works. I have tried to use string uri drawable but it can only display one image for all.
Previously, I had been looking for references on google and find so many tutorials. But I still don't get which part should I add or change. Can somebody help my problem?
This is my works.
TabGambar.java
public class TabGambar extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.tabgambar, container, false);
configureTextView(view);
return view;
}
private void configureTextView(View view) {
// TODO Auto-generated method stub
TextView namapenyakit = (TextView) view.findViewById(R.id.namapenyakit);
ImageView gambarpenyakit = (ImageView) view.findViewById(R.id.gambarpenyakit);
Bundle b = getActivity().getIntent().getExtras();
if (b != null)
{
namapenyakit.setText(b.getString("nama_penyakit"));
String uri = "#drawable/ayam1";
int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
gambarpenyakit.setImageDrawable(res);
}
}
}
DBAdapter.java
public class DBAdapter extends SQLiteAssetHelper {
//nama database, versi, dan nama tabel yang akan dibuat.
private static final String DATABASE_NAME = "pakarayam";
private static final int DATABASE_VERSION = 1;
private static final String tabel_gejala = "gejala";
public static final String kd_gejala = "kode_gejala";
public static final String nm_gejala = "nama_gejala";
private static final String tabel_penyakit = "penyakit";
public static final String kd_penyakit = "kode_penyakit";
public static final String nm_penyakit = "nama_penyakit";
public static final String deskripsi = "deskripsi";
public static final String solusi = "solusi";
public static final String gambar = "gambar";
private static final String tabel_rule = "rule";
public static final String kd_rule = "kode_rule";
public static final String ko_gejala = "kode_gejala";
public static final String ko_penyakit = "kode_penyakit";
public static final String nilai_mb = "nilai_mb";
public static final String nilai_md = "nilai_md";
private static DBAdapter dbInstance;
private static SQLiteDatabase db;
private DBAdapter(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBAdapter getInstance(Context context)
{
if (dbInstance == null)
{
dbInstance = new DBAdapter(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
#Override
public synchronized void close()
{
super.close();
if (dbInstance != null)
{
dbInstance.close();
}
}
public ArrayList<Gejala> getAllGejala()
{
ArrayList<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {kd_gejala, nm_gejala
}, null, null, null, null, nm_gejala);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
gejala.setKode_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(kd_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Gejala> Search(String Nama_gejala)
{
List<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {
kd_gejala,
nm_gejala },
nm_gejala + " like ?", new String[] {"%"+ Nama_gejala +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Penyakit> getAllPenyakit()
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {kd_penyakit, nm_penyakit, deskripsi, solusi, gambar
}, null, null, null, null, nm_penyakit);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public List<Penyakit> Searching (String Nama_penyakit)
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {
kd_penyakit,
nm_penyakit,
deskripsi,
solusi,
gambar},
nm_penyakit + " like ?", new String[] {"%"+ Nama_penyakit +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public double getMB(/*int kode_rule,*/ String kode_gejala)
{
/*
Cursor cursor = db.query(tabel_rule, new String[]
{kd_rule, ko_gejala, ko_penyakit, nilai_mb, nilai_md
}, ko_gejala + " like ?", new String[] {"%"+ kode_gejala +"%"},
null, null, null, null);
double mb = 0;
cursor.moveToFirst();
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
} while (cursor.moveToNext());
}
*/
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double mb = 0;
if(cursor != null){
cursor.moveToFirst();
while(!cursor.isAfterLast()){
mb = cursor.getDouble(3);
}
}
return mb;
}
public double getMD(/*int kode_rule,*/ String kode_gejala)
{
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double md = 0;
// cursor.moveToFirst();
// md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
/*
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
} while (cursor.moveToNext());
}
*/
if(cursor != null){
cursor.moveToFirst();
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
System.out.print(nilai_md);
}
return md;
}
}
I'm not sure of the exact details here but basically, if you want to store images in your database you must store the information as a 'blob' of bytes.
You'll need to convert between bytes and Bitmap when you read from the DB and Bitmap and bytes when you want to write to the DB.
A URI is usually used for a file coming from your device storage or somewhere on a server/website etc.
If this is what you're looking for and you'd like more detailed help just let me know and I can provide more info.
I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps