Error: Cursor Finalized without Prior Close - java

I have a Google Map's based application on android.
In short the application works by: first entering some sample data (containing latitude/longitude pairs into a database), reads them and finally plots them on a map overlay.
This app works fine when I run it on Android 2.3.3 (Gingerbread) emulator as well as on my HTC Desire S.
But when I try the same application in a Android 4.0.3 (ICS) emulator (after making changes in manifest file for sdk version) I get an error Cursor Finalized without Prior Close() when I try to execute the activity. With a NullPointer Exception and the app crashes.
StackTrace pastebin is hereUpdated Method(s)
public int getAllEntries() {
//int entryCount;
Cursor cursorE = db.rawQuery("SELECT COUNT(LATS) FROM myPROmapData",
null);
try {
if (cursorE.moveToFirst()) {
return cursorE.getInt(0);
}
return cursorE.getInt(0);
} finally {
cursorE.close();
}
}
--
public Double[] PopulateLats() {
//id = getAllEntries();
int LatcolumnIndex = 0;
Cursor cursor = db.rawQuery("SELECT LATS FROM myPROmapData", null);
try {
Double myLats[] = new Double[cursor.getCount()];;
if (cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++)
{
myLats[i] = cursor.getDouble(LatcolumnIndex);
cursor.moveToNext();
//cursor.close();
}
}
return myLats;
} finally {
cursor.close();
}
}
--
public Double[] PopulateLons(){
int LoncolumnIndex = 0;
Cursor cursor2 = db.rawQuery("SELECT LONS FROM myPROmapData", null);
try {
Double myLons[] = new Double[cursor2.getCount()];;
if (cursor2.moveToFirst()) {
for (int i = 0; i < cursor2.getCount(); i++)
{
myLons[i] = cursor2.getDouble(LoncolumnIndex);
cursor2.moveToNext();
//cursor.close();
}
}
return myLons;
} finally {
cursor2.close();
}
}
Here's my activity code:
public class MapMaster extends MapActivity {
/** Called when the activity is first created. */
private List mapOverlays;
private Projection projection;
private MapController mc;
private MapView mapView;
private GeoPoint gP;
// private GeoPoint gP2;
private MyOverlay myoverlay;
//Author: Kanishk
DBAdapter db = new DBAdapter(this);
public Double GetStartLat4gp()
{
Double Lat1 = null;
db.open();
//db.insertQuote(); //INSERTING SAMPLE DATA INTO TABLE
Double[] dtaStartLat = null;
dtaStartLat = db.PopulateLats();
for(int z=0;z<(dtaStartLat.length);z++)
{
//System.out.println("START_LAT:");
//System.out.println(dtaStartLat[z]);
Lat1 = dtaStartLat[z];
break;
}
db.close();
return Lat1;
}
public Double GetStartLon4gp()
{
Double Lon1 = null;
db.open();
//db.insertQuote(); //INSERTING SAMPLE DATA INTO TABLE
Double[] dtaStartLon = null;
dtaStartLon = db.PopulateLons();
for(int z=0;z<(dtaStartLon.length);z++)
{
//System.out.println("START_LAT:");
//System.out.println(dtaStartLon[z]);
Lon1 = dtaStartLon[z];
break;
}
db.close();
return Lon1;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_master);
//Double myStartLat = null;
//Double myStartLon = null;
mapView = (MapView) findViewById(R.id.mapview1);// Creating an instance
// of MapView
mapView.setBuiltInZoomControls(true);// Enabling the built-in Zoom
// Controls
//mapView.setTraffic(true);
//mapView.setStreetView(true);
GeoPoint gP = new GeoPoint((int)(GetStartLat4gp() * 1E6), (int)(GetStartLon4gp() * 1E6));
//gP = new GeoPoint(28570000, 77320000);// Creating a GeoPoint
System.out.println("v START CORDS v");
System.out.println(GetStartLat4gp());
System.out.println(GetStartLon4gp());
System.out.println("^ START CORDS ^");
mc = mapView.getController();
mc.setCenter(gP);
mc.setZoom(15);// Initializing the MapController and setting the map to
// center at the
// defined GeoPoint
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
myoverlay = new MyOverlay();
mapOverlays.add(myoverlay);
db.open();
//db.CreateSampleData(); //create sample data
//db.SyncNclean(); //SYNC - CLEAN
if(db.doesDatabaseExist(this, "PROdb")){
Toast.makeText(this, "EXISTS", Toast.LENGTH_SHORT).show();
db.SyncNclean();
Toast.makeText(this, "CLEANING..CREATING SAMPLE DATA..", Toast.LENGTH_SHORT).show();
db.CreateSampleData();
Toast.makeText(this, "Sample Data Created", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "DOES NOT EXISTS", Toast.LENGTH_SHORT).show();
db.SyncNclean();
Toast.makeText(this, "CLEANING..CREATING SAMPLE DATA..", Toast.LENGTH_SHORT).show();
db.CreateSampleData();
Toast.makeText(this, "Sample Data Created", Toast.LENGTH_SHORT).show();
}
long id = 0;
id = db.getAllEntries();
CharSequence text = "The data was added successfully!\nData Totals = " + id + "Records";
System.out.println(text);
db.close();
}
public Double[] GetLats()
{
db.open();
//db.insertQuote(); //INSERTING SAMPLE DATA INTO TABLE
Double[] dtaMyLats = null;
dtaMyLats = db.PopulateLats();
for(int z=0;z<(dtaMyLats.length);z++)
{
System.out.println("LATS:");
System.out.println(dtaMyLats[z]);
}
db.close();
return dtaMyLats;
}
public Double[] GetLons()
{
db.open();
Double[] dtaMyLons = null;
dtaMyLons = db.PopulateLons();
for(int z=0;z<(dtaMyLons.length);z++)
{
System.out.println("LONS:");
System.out.println(dtaMyLons[z]);
}
db.close();
return dtaMyLons;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class MyOverlay extends Overlay {
public MyOverlay() {
}
//Author: Kanishk
public void draw(Canvas canvas, MapView mapv, boolean shadow) {
super.draw(canvas, mapv, shadow);
// Configuring the paint brush
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
Double[] LatArr = GetLats();
Double[] LonArr = GetLons();
//generate geopoints dynamically based on coordinates from index # array
//author: Kanishk
int count = LatArr.length;
//System.out.println(count);
for(int i=0;i<count-1;i++)
{
Double lat1;
Double lon1;
Double lat2;
Double lon2;
lat1 = LatArr[i];
lon1 = LonArr[i];
//System.out.println(LatLon[i][j]);
/*System.out.println("<< BREAK >>");
System.out.println(lat1);
System.out.println(lon1);
*/
lat2=LatArr[i+1];
//lat1 = null;
lon2=LonArr[i+1];
//lon1 = null;
//i++;
if(lat2!=null){
GeoPoint gp1 = new GeoPoint((int)(lat1 * 1E6), (int)(lon1 * 1E6)); //
GeoPoint gp2 = new GeoPoint((int)(lat2 * 1E6), (int)(lon2 * 1E6)); //
System.out.println("<< coord1 >>");
System.out.println(lat1);
System.out.println(lon1);
System.out.println("<< coord2 >>");
System.out.println(lat2);
System.out.println(lon2);
Point p11 = new Point();
Point p22 = new Point();
Path mypath = new Path();
projection.toPixels(gp1, p11);
projection.toPixels(gp2, p22);
mypath.moveTo(p22.x, p22.y);// *
mypath.lineTo(p11.x, p11.y);// *
canvas.drawPath(mypath, mPaint);
}
}
// logic end
}
}
}
DBAdapter Class:
public class DBAdapter {
int id = 0;
//public static final String KEY_ROWID = "_id";
public static final String KEY_PHID = "phID";
public String KEY_LAT = "LATS";
public String KEY_LON = "LONS";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "PROdb";
private static final String DATABASE_TABLE = "myPROmapData";
private static final int DATABASE_VERSION = 9;
//private static final String DATABASE_CREATE = "create table myPROmapData (_id integer primary key autoincrement, phID integer, LATS real not null, LONS real not null);";
private static final String DATABASE_CREATE = "create table myPROmapData (phID integer, LATS real not null, LONS real not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
}
catch (Exception e){
Log.e(TAG,"Error: onCreate db");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS myPROmapData");
onCreate(db);
}
catch (Exception e){
Log.e(TAG,"Error: onUpgrade db");
}
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert sample data into the database---
public long CreateSampleData() {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PHID, 100);
initialValues.put(KEY_LAT, 28.4588);
initialValues.put(KEY_LON, 77.0725);
db.insert(DATABASE_TABLE, null, initialValues);
initialValues.put(KEY_LAT, 28.4719);
initialValues.put(KEY_LON, 77.0722);
db.insert(DATABASE_TABLE, null, initialValues);
/*initialValues.put(KEY_LAT, 28.5700);
initialValues.put(KEY_LON, 77.3200);*/
initialValues.put(KEY_LAT, 28.4795);
initialValues.put(KEY_LON, 77.0800);
db.insert(DATABASE_TABLE, null, initialValues);
/*initialValues.put(KEY_LAT, 28.4700);
initialValues.put(KEY_LON, 77.0300);*/
initialValues.put(KEY_LAT, 28.4813);
initialValues.put(KEY_LON, 77.0931);
db.insert(DATABASE_TABLE, null, initialValues);
/*initialValues.put(KEY_LAT, 27.1833);
initialValues.put(KEY_LON, 78.0167);*/
initialValues.put(KEY_LAT, 28.4820);
initialValues.put(KEY_LON, 77.1023);
db.insert(DATABASE_TABLE, null, initialValues);
/*initialValues.put(KEY_LAT, 26.4583);
initialValues.put(KEY_LON, 80.3173);*/
initialValues.put(KEY_LAT, 28.4804);
initialValues.put(KEY_LON, 77.1251);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public int getAllEntries() {
//int entryCount;
Cursor cursorE = db.rawQuery("SELECT COUNT(LATS) FROM myPROmapData",
null);
if (cursorE.moveToFirst()) {
//entryCount = cursorE.getInt(0);
return cursorE.getInt(0);
//return entryCount;
}
// CLOSING CURSOR
cursorE.close();
return cursorE.getInt(0);
//return entryCount;
}
public boolean doesDatabaseExist(ContextWrapper context, String dbName) {
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
public void SyncNclean(){
Log.w(TAG, "Sync'ing with Master Server..");
//sync master server here
Log.w(TAG, "Sync Complete..");
//Log.w(TAG, "Cleaning old data..");
db.execSQL("DROP TABLE IF EXISTS myPROmapData");
DBHelper.onCreate(db);
Log.w(TAG, "Cleaning completed..");
}
public Double[] PopulateLats() {
//id = getAllEntries();
int LatcolumnIndex = 0;
Cursor cursor = db.rawQuery("SELECT LATS FROM myPROmapData", null);
Double myLats[] = new Double[cursor.getCount()];;
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
myLats[i] = cursor.getDouble(LatcolumnIndex);
cursor.moveToNext();
cursor.close();
}
}
// Original location for cursor.close()
return myLats;
}
public Double[] PopulateLons(){
int LoncolumnIndex = 0;
Cursor cursor2 = db.rawQuery("SELECT LONS FROM myPROmapData", null);
Double myLons[] = new Double[cursor2.getCount()];;
if (cursor2.moveToFirst())
{
for (int i = 0; i < cursor2.getCount(); i++)
{
myLons[i] = cursor2.getDouble(LoncolumnIndex);
cursor2.moveToNext();
cursor2.close(); //third try
}
// second tried here: cursor2.close();
}
// Original location for cursor.close()
//db.close();
return myLons;
}
}
Any help will be appreciated. Thanks for reading.

The solution to the nullpointer exception is:
GetStartLat4gp or GetStartLon4gp returns null.
Apart from that, the code will be more stable whenn you rewrite this method to
public int getAllEntries() {
//int entryCount;
Cursor cursorE = db.rawQuery("SELECT COUNT(LATS) FROM myPROmapData",
null);
try {
if (cursorE.moveToFirst()) {
return cursorE.getInt(0);
}
return cursorE.getInt(0);
} finally {
cursorE.close();
}
}
In the original draft of it, it did not close the cursor because it did return early.
use try {} finally { close resources } as a good style, to be sure to close all resources in any case (even unexpected exceptions)
Apart from that, move the close() of the other cursor back outside the loop, it will provoke errors inside the loop. (best, use try / finally there, too)

I believe its because your doing a return statement before the finally so in this case the finally never gets executed and therefore the database doesn't get closed
You should move get the value from the cursor and set it to a variable and then return the variable at the bottom of the function like below.
public int getAllEntries() {
//int entryCount;
Cursor cursorE = db.rawQuery("SELECT COUNT(LATS) FROM myPROmapData",
null);
int value = 0
try {
if (cursorE.moveToFirst()) {
value = cursorE.getInt(0);
}
value = cursorE.getInt(0);
} finally {
cursorE.close();
}
return value;
}
Also as a side line comment your db.rawQuey should also be within the the try statement otherwise if the query fails for whatever reason the app will force close.

Related

Android App: Error: Android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

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 */
}

Error when trying to use cursor to get integer values from SQLite in Android

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)));
}
}
}

Saving elements in SQLite Android

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()

how to display images from sqlite through drawable

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.

android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd

I'm beginner and I'm trying to to load contact from database by clicking a button in a fragment, and then save outgoing call also in database?
ContactsFragemt.java
public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
SimpleCursorAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.contact, container, false);
final Button Button = (Button) view.findViewById(R.id.load_button);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(getActivity());
//*************************** method for population main contacts listView *********************************//
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_uri = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
int position = 0;
int exist = 0;
boolean imageComp, nameComp;
String[] contactsData = sqlDataBaseHelper.getContacts(position);
while (exist == 0 && (contactsData[0] != (null) || contactsData[1] != (null) || contactsData[2] != (null))) // we are checking that if it is reached at the end or not
{
if (contactsData[1] != null) {
if (contactsData[1].equals(phNumber)) // will make update if we got matched with phone number and if any of ther other parameter is changed
{
if (contactsData[2] == null) {
// pic is null saved in data base and
if (image_uri != null) {
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
// then update new pic here
}
} else // but if their is pic
if (!contactsData[2].equals(image_uri)) { // and he/she update pic with a brand new picture then
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
}
if (contactsData[0] == null) {
// name is null saved in data base and
if (contactName != null) {
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
// then update new name here
}
} else // if name was saved previously in based
if (!contactsData[0].equals(contactName)) { //but the guy changed his name so
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
}
exist = 1;
}
}
position++;
contactsData = sqlDataBaseHelper.getContacts(position);
}
if (exist == 0) // means if number is not in the list then make update
{
long id = sqlDataBaseHelper.insertData1(contactName, phNumber, image_uri);
if (id < 0) {
Toast.makeText(getActivity(), "Data1 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Data1 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
}
String[] fromFieldNames = sqlDataBaseHelper.fromFieldName1();
int[] toViewIDs = sqlDataBaseHelper.toIds1();
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_items_view,
null,
fromFieldNames,
toViewIDs,0);
ListView mainList = (ListView) view.findViewById(R.id.main_list_view);
mainList.setAdapter(adapter);
getLoaderManager().initLoader(0, null, ContactsFragment.this);
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = ContentProvider.CONTENT_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader loader) {
adapter.swapCursor(null);
}
}
SimpleCursorAdapter.java
public class SimpleCursorAdapter extends android.widget.SimpleCursorAdapter {
Context mcontext;
String[] values;
Cursor cursor;
int[] to;
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.values = from;
this.to = to;
this.cursor = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(list_items_view, parent, false);
final ImageButton call = (ImageButton) view.findViewById(R.id.call);
ImageButton sms = (ImageButton) view.findViewById(R.id.sms);
final TextView contact_no = (TextView) view.findViewById(R.id.contact_no);
final TextView contactName = (TextView) view.findViewById(R.id.contact_name);
ImageView contactImage = (ImageView) view.findViewById(R.id.contact_image);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(mcontext);
//********************************** method for calling from app****************************/
call.setOnClickListener(new View.OnClickListener() { //when phone button is clicked
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(String.valueOf("tel:" + contact_no.getText().toString())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//*/
if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mcontext.startActivity(callIntent);//*/
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) { // for 12 hours format
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
Cursor c = mcontext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c.moveToNext() == true) {
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/outgoing_call.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
c.close();
}
});
//********************************** method for sending message from app****************************//
sms.setOnClickListener(new View.OnClickListener() { //when sms button is clicked
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + contact_no.getText().toString()));
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(smsIntent);
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
String duration = "000 000 000";
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/message_sent.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
});
//************************** Reading contact from SQLDataBase for each item*************************************//
String[] contactsData = sqlDataBaseHelper.getContacts(position);
if (contactsData[0] != (null)) {
contactName.setText(contactsData[0]);
contact_no.setText(contactsData[1]);
if (contactsData[2] == (null)) {
contactImage.setImageResource(R.drawable.w4j8n);
} else {
contactImage.setImageURI(Uri.parse(contactsData[2]));
}
}//*/
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
}
}
ContentProvider.java
public class ContentProvider extends android.content.ContentProvider {
public static final String PROVIDER_NAME = "com.example.asim.simpleviewpager"; //.contentprovider
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/ContactsDataBase");
private static final int CONTENTPROVIDERS = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "ContactsDataBase", CONTENTPROVIDERS);
}
SQLDataBaseAdapter sqlDataBaseAdapter;
#Override
public boolean onCreate() {
sqlDataBaseAdapter = new SQLDataBaseAdapter(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if (uriMatcher.match(uri) == CONTENTPROVIDERS) {
return sqlDataBaseAdapter.getAllContacts();
} else {
return null;
}
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
SQLDataBaseAdapter.java
public class SQLDataBaseAdapter {
SQLDataBaseHelper sqlDataBaseHelper;
public SQLDataBaseAdapter(Context context){
sqlDataBaseHelper = new SQLDataBaseHelper(context);
}
public long insertData1(String contactName, String contactNo, String pic){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.NO, contactNo);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE1_NAME,null,contentValues);
return id;
}
public long insertData2(String contactName, String duration, String time, String date, String pic ){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.DURATION, duration);
contentValues.put(SQLDataBaseHelper.TIME, time);
contentValues.put(SQLDataBaseHelper.DATE, date);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE2_NAME,null,contentValues);
return id;
}
public String[] getContacts(int position) {
String[] contactsData = new String[3];
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
String[] columns = {SQLDataBaseHelper.UID, SQLDataBaseHelper.NAME, SQLDataBaseHelper.PICTURE, SQLDataBaseHelper.NO};
Cursor cursor = db.query(SQLDataBaseHelper.TABLE1_NAME, columns, null, null, null, null, null);
cursor.moveToPosition(position);
int pos = cursor.getPosition();
int cnt = cursor.getCount();
int checkElement = cnt-pos;
if (checkElement > 0)
{
cursor.moveToPosition(position);
int nameColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NAME);
String name = cursor.getString(nameColumnIndex);
int noColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NO);
String contactNo = cursor.getString(noColumnIndex);
int picColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.PICTURE);
String picture = cursor.getString(picColumnIndex);
contactsData[0] = name;
contactsData[1] = contactNo;
contactsData[2] = picture;
} else
{
contactsData[0] = null;
contactsData[1] = null;
contactsData[2] = null;
}
cursor.close();
db.close();
return contactsData;
}
public void updateTable1 (String oldName, String newName, String oldPhoneNo, String NewPhoneNumber, String oldPic, String newPic) {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
if (oldName != newName) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, newName);
String[] whereArgs = {oldName};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NAME+" =? ",whereArgs);
}
if(oldPhoneNo!=NewPhoneNumber){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NO, NewPhoneNumber);
String[] whereArgs = {oldPhoneNo};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NO+" =? ",whereArgs);
}
if(oldPic!=newPic){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.PICTURE, NewPhoneNumber);
String[] whereArgs = {oldPic};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.PICTURE+" =? ",whereArgs);
}
}
public void deleteRowTable1()
{
}
public void updateTable2 ()
{
}
public void deleteRowTable2()
{
}
/////////////////////////////////////////////////////////////////////
public Cursor getAllContacts(){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return db.query(SQLDataBaseHelper.TABLE1_NAME, new String[] {
SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE},
null, null, null, null,
SQLDataBaseHelper.NAME + " asc ");
}
public SQLDataBaseAdapter open() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return this;
}
public Cursor getAllRows1() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
Cursor cursor = db.query(true, SQLDataBaseHelper.TABLE1_NAME, SQLDataBaseHelper.ALL_KEYS1, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public String[] fromFieldName1(){///
String[] fields = new String[] {SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE};
return fields;
}
public int[] toIds1(){
int[] toViewIds = new int[]{R.id.contact_name,R.id.contact_no,R.id.contact_image};
return toViewIds;
}
static class SQLDataBaseHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "ContactsDataBase";
private static final String TABLE1_NAME = "CALLS_TABLE1";
private static final String TABLE2_NAME = "LOGS_TABLE";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String NO = "ContactNo";
private static final String DURATION = "Duration";
private static final String PICTURE = "Picture";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String[] ALL_KEYS1 = new String[] {UID,NAME, NO, PICTURE};
private static final String CREATE_TABLE1 = "CREATE TABLE "+TABLE1_NAME+" (" +UID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+NO+" VARCHAR(255), "
+PICTURE+" VARCHAR(255));";
private static final String CREATE_TABLE2 = "CREATE TABLE "+TABLE2_NAME+" ("
+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+DURATION+" VARCHAR(255), "
+PICTURE+" VARCHAR(255), " +DATE+ " VARCHAR(255), "+TIME+ " VARCHAR(255));";
private static final String DROP_TABLE1 = "DROP TABLE IF EXIST"+ TABLE1_NAME ;
private static final String DROP_TABLE2 = "DROP TABLE IF EXIST"+ TABLE2_NAME ;
private Context context;
public SQLDataBaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE1);
Toast.makeText(context,"onCreate1 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
try {
db.execSQL(CREATE_TABLE2);
Toast.makeText(context,"onCreate2 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE1);
Toast.makeText(context,"onUpgrade1 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
try {
db.execSQL(DROP_TABLE2);
Toast.makeText(context,"onUpgrade2 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
}
}
and these are the errors
01-30 04:03:23.804 2702-2702/com.example.asim.simpleviewpager E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd
at android.content.res.Resources.getValue(Resources.java:1049)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at android.support.v4.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:195)
at android.support.v4.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:143)
In SimpleCursorAdapter.java, you have a method bindView() which overrides the same method from its parent class, but you don't put any code in that method. Deleting the method should fix the error. But if you plan to override how binding works in that method, you may want to put some code in there starting with something like
super.bindView(view, context, cursor);

Categories