how to display images from sqlite through drawable - java

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.

Related

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

How to make Sms Filter app for android 6

I apologize for conversation.
I am using Google Translator.
I am writing an application that displays text messages with specific numbers.
The numbers stored in the application's user.
*** My problem is that my app does not work on Android 4.4 and above.
Basically what I Should do ? thanks.
My step-by-step program :
Incoming sms:
public class IncomingSms extends BroadcastReceiver {
SmsManager smsManager = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentmessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentmessage.getDisplayMessageBody();
Log.i("payam", "senderNum=" + senderNum + " | msg=" + message);
DBAdapter db = new DBAdapter(context);
db.open();
List<sh_number> blocknumbers = db.getAllNUMBERItem();
db.close();
for (sh_number thisblocknumber : blocknumbers) {
if (senderNum.equals(thisblocknumber.getnumber())) {
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}
/*if(senderNum.equals("5554")){
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}else {
Toast.makeText(context, "senderNum="+senderNum+" | msg="+message,Toast.LENGTH_LONG).show();
}*/
}
}
}
}
NumberListAdapter :
public class NumberListAdapter extends ArrayAdapter<sh_number> {
List<sh_number> AllNumbers;
Context c;
public NumberListAdapter(Context c, List<sh_number> numbrs){
super(c, android.R.id.content, numbrs);
AllNumbers = numbrs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_number, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getname());
txt = (TextView)convertView.findViewById(R.id.Itm_number);
txt.setText(AllNumbers.get(position).getnumber());
return convertView;
}
MassageListAdapter :
public class MsgListAdapter extends ArrayAdapter<sh_msg> {
List<sh_msg> AllNumbers;
Context c;
public MsgListAdapter(Context c, List<sh_msg> msgs){
super(c, android.R.id.content, msgs);
AllNumbers = msgs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_msg, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getnumber());
txt = (TextView)convertView.findViewById(R.id.Itm_msg);
txt.setText(AllNumbers.get(position).getText());
txt = (TextView)convertView.findViewById(R.id.Itm_date);
txt.setText(AllNumbers.get(position).getDate());
return convertView;
}
Database :
public class DBAdapter {
public static final String DATABASE_NAME = "smsblkrdb";
static final int DATABASE_VERSION = 1;
static final String CREATE_MSGTABLE = "CREATE TABLE msgsTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" numberid integer(128),\n" +
"\"text\" text(128),\n" +
" date text(128)\n" +
");";
public static final String DATABASE_MSGTABLE = "msgsTable";
public static final String KEY_ID = "id";
public static final String KEY_NUMBERID = "numberid";
public static final String KEY_TEXT = "text";
public static final String KEY_DATE = "date";
static final String CREATE_NUMBERSTABLE = "CREATE TABLE numbersTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" name text(128),\n" +
" number text(128)\n" +
");";
public static final String DATABASE_NUMBERSTABLE = "numbersTable";
public static final String KEY_NAME = "name";
public static final String KEY_NUMBER = "number";
public static final String TAG = "EsfanduneLrn";
DatabaseHelper DBHelper;
final Context context;
SQLiteDatabase db;
String yek_Msgnam[] = {
KEY_ID, KEY_NUMBERID, KEY_TEXT, KEY_DATE
};
String yek_Numbernam[] = {
KEY_ID, KEY_NAME, KEY_NUMBER
};
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(CREATE_MSGTABLE);
db.execSQL(CREATE_NUMBERSTABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_MSGTABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NUMBERSTABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close() {
DBHelper.close();
}
//---insert a contact into the database---
public long insertSH_MSG(sh_msg thisMsg) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisMsg.getId()));
initialValues.put(KEY_NUMBERID, thisMsg.getnumber());
initialValues.put(KEY_TEXT, thisMsg.getText());
initialValues.put(KEY_DATE, thisMsg.getDate());
return db.insert(DATABASE_MSGTABLE, null, initialValues);
}
public long insertSH_NUMBER(sh_number thisNumbr) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisNumbr.getId()));
initialValues.put(KEY_NUMBER, thisNumbr.getnumber());
initialValues.put(KEY_NAME, thisNumbr.getname());
return db.insert(DATABASE_NUMBERSTABLE, null, initialValues);
}
//---retrieves all the contacts---
public List<sh_msg> getAllMSGItem() {
Cursor cursor = db.query(DATABASE_MSGTABLE, yek_Msgnam, null, null, null, null, null);
List<sh_msg> nams = cursorToList_SHMSG(cursor);
cursor.close();
return nams;
}
private List<sh_msg> cursorToList_SHMSG(Cursor cursor) {
List<sh_msg> nams = new ArrayList<sh_msg>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_msg nam = new sh_msg();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBERID)));
nam.setText(cursor.getString(cursor.getColumnIndex(KEY_TEXT)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public List<sh_number> getAllNUMBERItem() {
Cursor cursor = db.query(DATABASE_NUMBERSTABLE, yek_Numbernam, null, null, null, null, null);
List<sh_number> nams = cursorToList_SHNUMBER(cursor);
cursor.close();
return nams;
}
private List<sh_number> cursorToList_SHNUMBER(Cursor cursor) {
List<sh_number> nams = new ArrayList<sh_number>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_number nam = new sh_number();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setname(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBER)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public void removeNumber(int numberId) {
db.delete(DATABASE_NUMBERSTABLE, KEY_ID +" == "+numberId,null);
}

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

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

source not found when creating object

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

Categories