Related
Here is the problem...I have three different functions namely syncFirebaseContacts(); getAllContacts(); and compareContactUpdateList();. These function's execution order is very important because first function's output becomes input of another. As I have said I have placed these three function in my onCreate() method in sequence as described.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new AdoreDataSource(this);
datasource.open();
syncFirebaseContacts();
getAllContacts();
compareContactUpdateList();
.......
But while debugging I found out that although pointer points syncFirebaseContacts() first but the code of getAllContact() is executed first and then compareContactUpdateList() is executed and after that syncFirebaseContacts() code is executed.
private void getAllContacts() {
String contactNumber;
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//All Mapping Stuff to be done here..
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
lst2.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
}
private void syncFirebaseContacts() {
Firebase userLocationRef = new Firebase(Constants.FIREBASE_URL_USERS);
userLocationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dsp : dataSnapshot.getChildren()){
datasource.createContact(String.valueOf(dsp.getKey()));
lst1.add(String.valueOf(dsp.getKey()));
Log.e("Hello", String.valueOf(dsp.getKey()));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("Could not process", "Sorry");
}
});
}
private void compareContactsUpdateList() {
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2);
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
final ArrayList<ContactsList> contacts = new ArrayList<ContactsList>();
//List<SyncContacts> syncContacts = datasource.getAllContacts();
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
String nameOfContact = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
Log.d("Name ", nameOfContact + contactNumber);
for(int j =0; j < commonOfAll.size(); j++){
if(contactNumber.equals(commonOfAll)){
Log.d("Name ", nameOfContact);
contacts.add(new ContactsList(contactNumber, nameOfContact, R.mipmap.ic_launcher));
}
}
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
final ContactsAdapterTwo contactsAdapterTwo = new ContactsAdapterTwo(this, contacts);
final GridView gridView = (GridView) findViewById(R.id.grid);
gridView.post(new Runnable() {
public void run() {
gridView.setAdapter(contactsAdapterTwo);
}
});
}
As my problem is that I want to compare two lists which is done in compareContactsUpdateList() by the line
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2); as I found out that lst1 is always empty because syncFirebaseContacts() 's code is excuted at last
My applogies if my question length is too long or if my problem is trivial. But it is a big problem for me coz I am new to coding :-) please help me....Anyways Thanx in advance...
I want to display images from column 'images' in 'penyakit' table from sqlite database. That image display through TabGambar.java.
My friend told me than I can put address of image in database and save that image in drawable. But I don't understand how it works. I have tried to use string uri drawable but it can only display one image for all.
Previously, I had been looking for references on google and find so many tutorials. But I still don't get which part should I add or change. Can somebody help my problem?
This is my works.
TabGambar.java
public class TabGambar extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.tabgambar, container, false);
configureTextView(view);
return view;
}
private void configureTextView(View view) {
// TODO Auto-generated method stub
TextView namapenyakit = (TextView) view.findViewById(R.id.namapenyakit);
ImageView gambarpenyakit = (ImageView) view.findViewById(R.id.gambarpenyakit);
Bundle b = getActivity().getIntent().getExtras();
if (b != null)
{
namapenyakit.setText(b.getString("nama_penyakit"));
String uri = "#drawable/ayam1";
int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
gambarpenyakit.setImageDrawable(res);
}
}
}
DBAdapter.java
public class DBAdapter extends SQLiteAssetHelper {
//nama database, versi, dan nama tabel yang akan dibuat.
private static final String DATABASE_NAME = "pakarayam";
private static final int DATABASE_VERSION = 1;
private static final String tabel_gejala = "gejala";
public static final String kd_gejala = "kode_gejala";
public static final String nm_gejala = "nama_gejala";
private static final String tabel_penyakit = "penyakit";
public static final String kd_penyakit = "kode_penyakit";
public static final String nm_penyakit = "nama_penyakit";
public static final String deskripsi = "deskripsi";
public static final String solusi = "solusi";
public static final String gambar = "gambar";
private static final String tabel_rule = "rule";
public static final String kd_rule = "kode_rule";
public static final String ko_gejala = "kode_gejala";
public static final String ko_penyakit = "kode_penyakit";
public static final String nilai_mb = "nilai_mb";
public static final String nilai_md = "nilai_md";
private static DBAdapter dbInstance;
private static SQLiteDatabase db;
private DBAdapter(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBAdapter getInstance(Context context)
{
if (dbInstance == null)
{
dbInstance = new DBAdapter(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
#Override
public synchronized void close()
{
super.close();
if (dbInstance != null)
{
dbInstance.close();
}
}
public ArrayList<Gejala> getAllGejala()
{
ArrayList<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {kd_gejala, nm_gejala
}, null, null, null, null, nm_gejala);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
gejala.setKode_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(kd_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Gejala> Search(String Nama_gejala)
{
List<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {
kd_gejala,
nm_gejala },
nm_gejala + " like ?", new String[] {"%"+ Nama_gejala +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Penyakit> getAllPenyakit()
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {kd_penyakit, nm_penyakit, deskripsi, solusi, gambar
}, null, null, null, null, nm_penyakit);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public List<Penyakit> Searching (String Nama_penyakit)
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {
kd_penyakit,
nm_penyakit,
deskripsi,
solusi,
gambar},
nm_penyakit + " like ?", new String[] {"%"+ Nama_penyakit +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public double getMB(/*int kode_rule,*/ String kode_gejala)
{
/*
Cursor cursor = db.query(tabel_rule, new String[]
{kd_rule, ko_gejala, ko_penyakit, nilai_mb, nilai_md
}, ko_gejala + " like ?", new String[] {"%"+ kode_gejala +"%"},
null, null, null, null);
double mb = 0;
cursor.moveToFirst();
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
} while (cursor.moveToNext());
}
*/
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double mb = 0;
if(cursor != null){
cursor.moveToFirst();
while(!cursor.isAfterLast()){
mb = cursor.getDouble(3);
}
}
return mb;
}
public double getMD(/*int kode_rule,*/ String kode_gejala)
{
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double md = 0;
// cursor.moveToFirst();
// md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
/*
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
} while (cursor.moveToNext());
}
*/
if(cursor != null){
cursor.moveToFirst();
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
System.out.print(nilai_md);
}
return md;
}
}
I'm not sure of the exact details here but basically, if you want to store images in your database you must store the information as a 'blob' of bytes.
You'll need to convert between bytes and Bitmap when you read from the DB and Bitmap and bytes when you want to write to the DB.
A URI is usually used for a file coming from your device storage or somewhere on a server/website etc.
If this is what you're looking for and you'd like more detailed help just let me know and I can provide more info.
I'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);
I have the following code,but i'm having some trouble with duplicates.How can i modify the code so that it won't allow duplicates in the database ? I'm using it to power an AutoCompleteTextView so the duplicates aren't helping.
Thanks a lot !
package com.giantflyingsaucer;
import android.database.*;
import android.database.sqlite.*;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
public class SQLiteCountryAssistant extends SQLiteOpenHelper
{
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
" (_id integer primary key autoincrement, country_name text not null);)";
private SQLiteDatabase sqliteDBInstance = null;
public SQLiteCountryAssistant(Context context)
{
super(context, DB_NAME, null, DB_VERSION_NUMBER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO: Implement onUpgrade
}
#Override
public void onCreate(SQLiteDatabase sqliteDBInstance)
{
Log.i("onCreate", "Creating the database...");
sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
}
public void openDB() throws SQLException
{
Log.i("openDB", "Checking sqliteDBInstance...");
if(this.sqliteDBInstance == null)
{
Log.i("openDB", "Creating sqliteDBInstance...");
this.sqliteDBInstance = this.getWritableDatabase();
}
}
public void closeDB()
{
if(this.sqliteDBInstance != null)
{
if(this.sqliteDBInstance.isOpen())
this.sqliteDBInstance.close();
}
}
public long insertCountry(String countryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, countryName);
Log.i(this.toString() + " - insertCountry", "Inserting: " + countryName);
return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
}
public boolean removeCountry(String countryName)
{
int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "country_name='" + countryName + "'", null);
if(result > 0)
return true;
else
return false;
}
public long updateCountry(String oldCountryName, String newCountryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, newCountryName);
return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "country_name='" + oldCountryName + "'", null);
}
public String[] getAllCountries()
{
Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, null);
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
}
One option would be to call removeCountry from your insertCountry method before actually doing the insert. Alternatively you could modify your database structure to be country_name text not null unique. SQLite will then throw an exception if you fail the constraint which you'll need to catch and handle appropriately.
Finally, another option would be to attempt a query of the database for the string in question, if it exists, don't insert, if it doesn't then insert it.
You could use a function to see if the data already exists in the database.
public boolean checkIfDataExists(String country) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE_NAME, columns, null, null, null, null, null);
int iCountry = c.getColumnIndex(KEY_COUNTRY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
if (country.equals(c.getString(iCountry))) {
db.close();
return true;
}
}
db.close();
return false;
}
Call this function in an if statement and execute the insert instruction if the condition is not true.
I tried this and it works great,at least so far.
private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
" (_id integer primary key autoincrement, country_name text UNIQUE);)";
Added UNIQUE instead of not null
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.