I want to make simple recyclerview from external database but the app crashes. This is in the logcat:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
DatabaseAccess class:
public class DatabaseAccess {
private SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
private static DatabaseAccess instance;
private DatabaseAccess (Context context) {
this.openHelper = new MyDatabase(context);
}
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
public void open() {
this.database = this.openHelper.getWritableDatabase();
}
public void close() {
if (this.database!= null) {
this.database.close();
}
}
public ArrayList<CAR> getAllCars() {
ArrayList<CAR> cars = new ArrayList<>();
Cursor cursor = database.rawQuery(" SELECT * FROM " + MyDatabase.CAR_TB_NAME, null);
if (cursor != null && cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));
CAR c = new CAR(id,model,color,dpl);
cars.add(c);
}
while (cursor.moveToNext());
cursor.close();
}
return cars;
}
}
the error disappeared when I corrected that part of code
int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));
to
int id = cursor.getInt(0);
String model = cursor.getString(1);
String color = cursor.getString(2);
double dpl = cursor.getdouble(3);
Related
i have 57 radio button in list view, i want to divide those radio button into 19 groups, so each group has 3 radio button. but when i scrolled it the view is messed up and automatically adding radio button become double.
the data is gotten from sqlite database.
KlasifikasiActivity
public class KlasifikasiActivity extends AppCompatActivity {
private ListView lvKlasifikasi;
private ListKlasifikasiAdapter adapter;
private List<Klasifikasi> mKlasifikasiList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klasifikasi);
lvKlasifikasi = (ListView)findViewById(R.id.stepSwitcher);
mDBHelper = new DatabaseHelper(this);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if (false == database.exists()){
mDBHelper.getReadableDatabase();
if (copyDatabase(this)){
Toast.makeText(this,"COPY SUCCESS",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"COPY ERROR",Toast.LENGTH_SHORT).show();
return;
}
}
//get db metode
mKlasifikasiList = mDBHelper.getListKlasifikasiByGroup();
adapter = new ListKlasifikasiAdapter(this,mKlasifikasiList);
lvKlasifikasi.setAdapter(adapter);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0){
outputStream.write(buff,0,length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
DatabaseHelper and function method
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "database.db";
public static final String DBLOCATION = "/data/data/com.example.damar.finalproject/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context,DBNAME,null,1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if (mDatabase!=null){
mDatabase.close();
}
}
public List<Klasifikasi> getListKlasifikasiByGroup(){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi group by group_index", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return klasifikasiList;
}
}
have you checked list just after fetching from db and before set to adapter
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 have a problem, you can see below. Please, help me. I am beginner in Android App. Thank you in advance for your help. I am getting the following error:
ERROR: android.database.CursorIndexOutOfBoundsException: Index 0
requested, with a size of 0
I don't know how to solve it.
This is my database helper class:-
public class DbObsluha extends SQLiteOpenHelper{
private static String DB_JMENO = "Databaze.db";
private static String DB_CESTA ="";
private static final int DB_VERZE = 2;
private SQLiteDatabase databaze;
private Context mContext = null;
public DbObsluha(Context context) {
super(context, DB_JMENO, null, DB_VERZE);
DB_CESTA = context.getApplicationInfo().dataDir + "/databases/";
File file = new File(DB_CESTA + "Databaze.db");
if(file.exists())
otevreniDatabaze();
this.mContext = context;
/*
this.DB_CESTA = this.mContext.getDatabasePath(DB_JMENO).getAbsolutePath();
Log.e("Path 1", DB_CESTA);
*/
}
public void otevreniDatabaze() {
String mojeCesta = DB_CESTA + DB_JMENO;
databaze = SQLiteDatabase.openDatabase(mojeCesta, null, SQLiteDatabase.OPEN_READWRITE);
}
public void kopirovanoDatabaze() throws IOException {
try {
InputStream mujVstup = mContext.getAssets().open(DB_JMENO);
String vystupniNazevSouboru = DB_CESTA + DB_JMENO;
OutputStream mujVystup = new FileOutputStream(vystupniNazevSouboru);
byte[] buffer = new byte[1024];
int velikost;
while((velikost = mujVstup.read(buffer)) > 0)
mujVystup.write(buffer, 0, velikost);
mujVystup.flush();
mujVystup.close();
mujVstup.close();
}catch (Exception e){
e.printStackTrace();
}
}
private boolean overeniDataze() {
SQLiteDatabase tempDB = null;
try {
String mojeCesta = DB_CESTA + DB_JMENO;
tempDB = SQLiteDatabase.openDatabase(mojeCesta, null, SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException e) {
e.printStackTrace();
}
if(tempDB != null)
{
tempDB.close();
}
return tempDB != null ? true : false;
}
public void vytvoreniDatabaze() throws IOException {
boolean existenceDatabaze = overeniDataze();
if (existenceDatabaze) {
}else {
this.getReadableDatabase();
try {
kopirovanoDatabaze();
}catch (IOException e) {
e.printStackTrace();
}
}
}
/*
#Override
public synchronized void close() {
if(databaze != null)
databaze.close();
super.close();
}
*/
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion>oldVersion)
try {
kopirovanoDatabaze();
} catch (IOException e) {
e.printStackTrace();
}
}
//zobrazenu for table
public List<Otazky> vsechnyOtazky(){
List<Otazky> seznamOtazek = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM Otazky ORDER BY Random()", null);
if(c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("ID"));
String Otazka = c.getString(c.getColumnIndex("Otazka"));
String OdpovedA = c.getString(c.getColumnIndex("OdpovedA"));
String OdpovedB = c.getString(c.getColumnIndex("OdpovedB"));
String OdpovedC = c.getString(c.getColumnIndex("OdpovedC"));
String OdpovedD = c.getString(c.getColumnIndex("OdpovedD"));
String Vysledek = c.getString(c.getColumnIndex("Vysledek"));
Otazky otazky = new Otazky(Id, Otazka, OdpovedA, OdpovedB, OdpovedC, OdpovedD, Vysledek);
seznamOtazek.add(otazky);
}
while (c.moveToNext());
c.close();
}catch (Exception e){
e.printStackTrace();
}
db.close();
return seznamOtazek;
}
//upraveni pro aktivitu Hra
public List<Otazky> vsechnyOtazkyUroven(String uroven){
List<Otazky> seznamOtazek = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
int konec = 0;
if(uroven.equals(Urovne.UROVEN.LEHKÁ.toString()))
konec = 5;
else if(uroven.equals(Urovne.UROVEN.STŘEDNÍ.toString()))
konec = 10;
else if(uroven.equals(Urovne.UROVEN.TĚŽKÁ.toString()))
konec = 15;
else if(uroven.equals(Urovne.UROVEN.LEGENDÁRNÍ.toString()))
konec = 20;
try {
c = db.rawQuery(String.format("SELECT * FROM Otazky ORDER BY Random() LIMIT %d", konec), null);
if(c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("ID"));
String Otazka = c.getString(c.getColumnIndex("Otazka"));
String OdpovedA = c.getString(c.getColumnIndex("OdpovedA"));
String OdpovedB = c.getString(c.getColumnIndex("OdpovedB"));
String OdpovedC = c.getString(c.getColumnIndex("OdpovedC"));
String OdpovedD = c.getString(c.getColumnIndex("OdpovedD"));
String Vysledek = c.getString(c.getColumnIndex("Vysledek"));
Otazky otazky = new Otazky(Id, Otazka, OdpovedA, OdpovedB, OdpovedC, OdpovedD, Vysledek);
seznamOtazek.add(otazky);
}while (c.moveToNext());
c.close();
}catch (Exception e){
e.printStackTrace();
}
db.close();
return seznamOtazek;
}
//Vložení skore do žebříčku
public void vlozeniSkore(double skore){
/*SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Skore", Skore);
db.insert("Zebricek", null, contentValues);
*/
String query = "INSERT INTO Zebricek(Skore) VALUES("+ skore +")";
databaze.execSQL(query);
}
//get score and sort ranking
public List<Zebricek> getZebricek(){
List<Zebricek> seznamZebricku = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM Zebricek ORDER BY Skore DESC", null);
if (c == null) return null;
c.moveToNext();
do {
int Id = c.getInt(c.getColumnIndex("ID"));
double Skore = c.getDouble(c.getColumnIndex("Skore"));
Zebricek zebricek = new Zebricek(Id, Skore);
seznamZebricku.add(zebricek);
}while (c.moveToNext());
c.close();
}catch (Exception e){
e.printStackTrace();
}
db.close();
return seznamZebricku;
}
}
This is the Activity Class :-
public class Hra extends AppCompatActivity implements View.OnClickListener{
final static long INTERVAL = 1000; // 1 sekunda
final static long KONEC = 7000; // 7 sekund
int meziSkore = 0;
CountDownTimer countDownTimer; //odpočítavadlo pro meziSkore
List<Otazky> otazkyHra = new ArrayList<>(); // všechny otazky
DbObsluha db;
int index = 0, skore = 0, thisOtazka = 0, vsechnyOtazky, spravnaOdpoved;
String uroven="";
//Ovládání
ProgressBar progressBar;
Button btnA, btnB, btnC, btnD;
TextView txtSkore, txtOtazka, txtZadani;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hra);
//data z hlavní aktivity
Bundle extra = getIntent().getExtras();
if(extra != null)
uroven = extra.getString("UROVEN");
db = new DbObsluha(this);
txtSkore = (TextView)findViewById(R.id.txtSkore);
txtOtazka = (TextView)findViewById(R.id.txtOtazka);
txtZadani = (TextView)findViewById(R.id.txtZadani);
progressBar = (ProgressBar)findViewById(R.id.progessBar);
btnA = (Button)findViewById(R.id.btnOdpovedA);
btnB = (Button)findViewById(R.id.btnOdpovedB);
btnC = (Button)findViewById(R.id.btnOdpovedC);
btnD = (Button)findViewById(R.id.btnOdpovedD);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
otazkyHra = db.vsechnyOtazkyUroven(uroven);
vsechnyOtazky = otazkyHra.size();
countDownTimer = new CountDownTimer(KONEC, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(meziSkore);
meziSkore++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
ukazOtazku(++index);
}
};
ukazOtazku(index);
}
private void ukazOtazku(int index) {
if(index < vsechnyOtazky)
{
thisOtazka++;
txtOtazka.setText(String.format("%d/%d", thisOtazka, vsechnyOtazky));
progressBar.setProgress(0);
meziSkore = 0;
txtZadani.setText(otazkyHra.get(index).getOtazka());
btnA.setText(otazkyHra.get(index).getOdpovedA());
btnB.setText(otazkyHra.get(index).getOdpovedB());
btnC.setText(otazkyHra.get(index).getOdpovedC());
btnD.setText(otazkyHra.get(index).getOdpovedD());
countDownTimer.start();
}
else{
Intent intent = new Intent(this,Vysledek.class);
Bundle odeslaniDat = new Bundle();
odeslaniDat.putInt("SKORE",skore);
odeslaniDat.putInt("VSECHNYOTAZKY",vsechnyOtazky);
odeslaniDat.putInt("SPRAVNAODPOVED",spravnaOdpoved);
intent.putExtras(odeslaniDat);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if(index < vsechnyOtazky){
Button zmacknuteTlacitko = (Button)v;
if(zmacknuteTlacitko.getText().equals(otazkyHra.get(index).getVysledek()))
{
skore+=10; //zvětšení skore
spravnaOdpoved++; //zvětšená správné odpovědi
ukazOtazku(++index);
}
else {
ukazOtazku(++index); // pokud zvolí dobře, následuje další otázka
}
txtSkore.setText(String.format("%d", skore));
}
}
}
enter image description here
Your cursor is empty. You can't read any data from an empty cursor, hence the exception.
Both, moveToFirst() and moveToNext() will return false if the move did not succeed. You're ignoring the result of moveToFirst() and try reading from the cursor leading to the exception.
When you use a database, it is best to check for records before looping to retrieve them (if any).
The best way to do this is to use the getCount method of the Cursor class.
Cursor c = db.rawQuery(String.format("SELECT * FROM Otazky ORDER BY Random() LIMIT %d", konec), null);
if (c != null && c.getCount() > 0) {
/* Code Here */
}
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 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.