Hi am new to android and would like some help. So in my app I am fetching data from an xml file on a server and storing it in a database. I manually checked the database and all went well. Now when I am trying to read the data from the connectToDB() method in ActivityTwo class I see no data on the screen but when I read the data from the offlineDatabase() in the same class, I see the data perfectly on the screen. I am completely baffled by this situation. Any help would be immensely appreciated. BTW: connectToDB() is called when the user is online and offlineDatabase() is called when the user is offline.
ActivityTwo.java
public class ActivityTwo extends Activity {
private ArrayList<String> eventsList = new ArrayList<String>();
private HandleXML handleXML;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
if(netCheckPls() == false) {
new AlertDialog.Builder(this)
.setTitle("Internet Connection")
.setMessage("Not connected to the Internet!")
.setCancelable(true)
.setPositiveButton(R.string.ok, null)
.show();
offlineDatabase();
} else {
connectToDB();
}
}
#Override
public void onDestroy() {
//eventsData.close();
}
public void offlineDatabase() {
DBHelper dHelper = new DBHelper(this);
eventsList = dHelper.getAllEvents();
addMoreRows();
}
public void connectToDB() {
handleXML = new HandleXML(this, "http://eamplesite/example.xml");
handleXML.fetchXML();
//while(handleXML.parsingComplete);
//;
eventsList = handleXML.arrayList();
addMoreRows();
//offlineDatabase();
}
public void addMoreRows() {
TableLayout tl = (TableLayout)findViewById(R.id.linearLayout);
for(int i = 0; i < eventsList.size(); i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("#FFFFFF"));
tv.setText((String)eventsList.get(i));
row.addView(tv);
tl.addView(row);
}
}
public boolean netCheckPls() {
Context ctx = this;
ConnectivityManager connec = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Check if wifi or mobile network is available or not. If any of them is
// available or connected then it will return true, otherwise false;
return wifi.isConnected() || mobile.isConnected();
}
}
HandleXML.java
public class HandleXML extends Activity {
private String title = "title";
private String link = "link";
private String description = "description";
private DBHelper dbHelper;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> links = new ArrayList<String>();
private ArrayList<String> descriptions = new ArrayList<String>();
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(Context context, String url){
context.deleteDatabase("EventsDB.db");
dbHelper = new DBHelper(context);
this.urlString = url;
}
public ArrayList<String> arrayList() {
return dbHelper.getAllEvents();
}
public String getTheTitle(){
return title;
}
public String getLink(){
return link;
}
public String getDescription(){
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
titles.add(text);
}
else if(name.equals("guid")){
link = text;
links.add(text);
}
else if(name.equals("description")){
description = text;
descriptions.add(text);
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
//dbHelper.insertEvents(title, description, link);
addToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToDB() {
for(int i = 0; i < titles.size(); i++) {
dbHelper.insertEvents(titles.get(i), descriptions.get(i), links.get(i));
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e) {
}
}
});
thread.start();
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EventsDB.db";
public static final String EVENTS_TITLE = "title";
public static final String EVENTS_DESCRIPTION = "decription";
public static final String EVENTS_LINK = "link";
public static final String EVENTS_TABLE_NAME = "events";
public static final String EVENTS_COLUMN_NAME = "title";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table events " +
"(id integer primary key, title text, description text, link text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS events");
onCreate(db);
}
public boolean insertEvents (String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.insert("events", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events where id=" + id + "", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, EVENTS_TABLE_NAME);
return numRows;
}
public boolean updateEvents (Integer id, String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.update("events", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
/*public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}*/
public ArrayList getAllEvents()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(EVENTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
events.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/bg2">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:orientation="vertical">
</TableLayout>
</ScrollView>
</LinearLayout>
FYI the reason I want to delete the database, when the user comes online, is that I want to prevent similar data being added to the database (which I found was happening). Again would greatly appreciate some light on this matter. Thank You!
Your HandleXML class is calling context.deleteDatabase("EventsDB.db"); in its constructor.
Related
I have my databasehelper,model and mainactivity but the data is still not displaying. I don't know what is wrong or missing from my code.
This is the data sqlite which I browse using DB Browser for SQLite
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.jathniel.myapplication/databases/";
private static String DB_NAME = "mydoctorfinder_new_migrate.sqlite";
private SQLiteDatabase myDataBase;
private Context myContext = null;
public static String TAG = "tag";
private static final String TABLE_DOCTORS = "doctors";
private static final String KEY_ID = "id";
private static final String KEY_FULLNAME = "full_name";
private static final String KEY_GENDER = "gender";
public DatabaseHelper(Context context) {
super(context, DB_NAME, (SQLiteDatabase.CursorFactory) null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = this.checkDataBase();
if(!dbExist) {
this.getReadableDatabase();
try {
this.copyDataBase();
} catch (IOException e) {
throw new Error("Error");
}
}
}
public void copyDataBase() throws IOException {
InputStream myInput = this.myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
FileOutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String e = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(e, (SQLiteDatabase.CursorFactory)null, 0);
} catch (SQLiteException e) {
;
}
if(checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
this.myDataBase = SQLiteDatabase.openDatabase(myPath, (SQLiteDatabase.CursorFactory)null, 0);
}
public synchronized void close() {
if(this.myDataBase != null) {
this.myDataBase.close();
}
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDatabase() {
}
public List<DoctorModel> getAllDoctorList() {
List<DoctorModel> doctorsArrayList = new ArrayList<DoctorModel>();
String selectQuery = "SELECT * FROM " + TABLE_DOCTORS;
Log.d(TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
DoctorModel doctor = new DoctorModel();
doctor.id = c.getInt(c.getColumnIndex(KEY_ID));
doctor.full_name = c.getString(c.getColumnIndex(KEY_FULLNAME));
doctor.gender = c.getString(c.getColumnIndex(KEY_GENDER));
doctorsArrayList.add(doctor);
} while (c.moveToNext());
}
return doctorsArrayList;
}
}
Model class
public class DoctorModel {
public int id;
public String full_name;
public String gender;
public DoctorModel(){
}
public DoctorModel(int id, String full_name, String gender) {
// TODO Auto-generated constructor stub
this.id = id;
this.full_name = full_name;
this.gender = gender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
List<DoctorModel> list = new ArrayList<DoctorModel>();
DatabaseHelper db;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(getApplicationContext());
tv = (TextView) findViewById(R.id.tv);
print(db.getAllDoctorList());
}
private void print(List<DoctorModel> list) {
// TODO Auto-generated method stub
String value = "";
for(DoctorModel dm : list){
value = value+"id: "+dm.id+", fullname: "+dm.full_name+" Gender: "+dm.gender+"\n";
}
tv.setText(value);
}
}
You forget to add DoctorModel Object in doctorsArrayList under getAllDoctorList()
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
DoctorModel doctor = new DoctorModel();
doctor.id = c.getInt(c.getColumnIndex(KEY_ID));
doctor.full_name = c.getString(c.getColumnIndex(KEY_FULLNAME));
doctor.gender = c.getString(c.getColumnIndex(KEY_GENDER));
doctorsArrayList.add(doctor); // add Object in ArrayList
} while (c.moveToNext());
}
When do you use: private void print(List list) ?
Not when opening the application.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(getApplicationContext());
tv = (TextView) findViewById(R.id.tv);
// ADD THIS LINE:
// NOW THIS WILL RUN WHEN OPENING/RUNNING THE APPLICATION
print(db.getAllDoctorList());
}
As my first Android project I'm trying to make an RSS reader app in which Listview items can be saved to SQLite, allowing them to be read offline. However, when trying to return news titles in a listView using a query with SimpleCursorAdapter, the listview displays the text "title", rather than the actual title of the news.
This seems to suggest that the items are not being stored to the database, or that the content values are not being properly assigned.
Can anybody see where i might be going wrong?
Thanks in advance!
RssItem.java
public class RssItem {
protected String _id;
public String title;
protected String link;
protected String page;
protected String completeTextLink;
protected String mainBody;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
//Title get/set
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//Link get/set
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
//CompleteTextLink get/set
public String getCompleteTextLink() {
return completeTextLink;
}
public void setCompleteTextLink(String completeTextLink) {
this.completeTextLink = completeTextLink;
}
//MainBody get/set
public String getMainBody() {
return mainBody;
}
public void setMainBody(String mainBody) {
this.mainBody = mainBody;
}
//Page get/set
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
#Override
public String toString() {
return title;
}}
MainActivity.java
public class MainActivity extends Activity {
private MainActivity local;
private DatabaseHandler db;
//Method to create main application view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//**************************create a button to move to the user's saved feeds screen*****************************
Button myFeedsButton = (Button) findViewById(R.id.myFeedsButton);
myFeedsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this, MyFeedsScreen.class));
}
});
//***************************************************************************************************************
//Create new instance of database handler
db = new DatabaseHandler(this);
//set local ref to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
//start download Rss task - execute method calls the
task.execute("http://feeds.bbci.co.uk/news/rss.xml?edition=uk");
//debug thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
}
//*******************************************************************************************************************
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem>>
{
#Override
protected List<RssItem> doInBackground(String... urls) {
//debug task thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
try {
//create a new reader
RssReader rssReader = new RssReader(urls[0]);
//Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("RssReaderApp", e.getMessage());
}
return null;
}//doInBackground
//is invoked on UI thread after background tasks are complete.
// Results of background task are passed here as a parameter
#Override
protected void onPostExecute(List<RssItem> result)
{
//Gets listview from main.xml
final ListView listItems = (ListView) findViewById(R.id.listMainView);
//Creates a new list adapter - displays an array of strings in listview
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local, android.R.layout.simple_list_item_1, result);
//Set list adapter for listView
listItems.setAdapter(adapter);
//OnItemClick listener set to allow user to access content from title
listItems.setOnItemClickListener(new ListListener(result, local));
//*******************************LONG CLICK FUNCTIONALITY******************************************
//Set new long click listener which should allow item to be stored to db
listItems.setLongClickable(true);
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
try {
db.open();
RssItem item = new RssItem();
item.title = "title";
item.link = "link";
item.completeTextLink ="completeTextLink";
item.page = "page";
db.insertRssItem(item);
db.close();
} catch (SQLException e)
{
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Item saved in My Feeds!", Toast.LENGTH_SHORT).show();
return true;
}
});
}//onPostExecute
}}//class
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "news_db";
public static SQLiteDatabase db;
private static final int DATABASE_VERSION = 32;
protected static final String TABLE_NEWS = "news";
private static final String TAG = "TAG";
private static final String TAG1 = "TAG1";
static String columnTitle = "title";
protected static final String _id = "_id";
//Methods for tables
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_NEWS = "CREATE TABLE " + TABLE_NEWS + "(_id VARCHAR, title TEXT, link TEXT, completeTextLink TEXT, mainBody Text, page TEXT)";
db.execSQL(CREATE_TABLE_NEWS);
Log.w(TAG, "Database has been created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWS);
onCreate(db);
}
public void open() throws SQLException {
db = this.getWritableDatabase();
}
//Method to insert new rssItem object to the database
public void insertRssItem(RssItem rssItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", rssItem._id);
contentValues.put("title", rssItem.title);
contentValues.put("link", rssItem.link);
contentValues.put("mainBody", rssItem.mainBody);
contentValues.put("completeTextLink", rssItem.completeTextLink);
contentValues.put("page", rssItem.page);
db.insert(TABLE_NEWS, "title", contentValues);
Log.d(TAG1, "ITEM SAVED IN DATABASE!!!");
}//insert item method
//Method to return all news for a given item
public List<RssItem> getAllNewsForItem(String page) {
List<RssItem> SavedNewsList = new ArrayList<RssItem>();
Cursor cursor = db.rawQuery("select _id, completeTextLink, title, link, mainBody, page" +
" FROM " + TABLE_NEWS + " where page = ?", new String[]{page});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
RssItem rssItem = new RssItem();
rssItem._id = cursor.getString(0);
rssItem.completeTextLink = cursor.getString(1);
rssItem.title = cursor.getString(2);
rssItem.link = cursor.getString(3);
rssItem.mainBody = cursor.getString(4);
rssItem.page = page;
SavedNewsList.add(rssItem);
cursor.moveToNext();
}
cursor.close();
return SavedNewsList;
}
//get data from database for listview
public Cursor getData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NEWS, null);
return cursor;
}}
MyFeedsScreen.java
public class MyFeedsScreen extends ListActivity {
DatabaseHandler dbHandler;
SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_feeds_screen);
dbHandler = new DatabaseHandler(MyFeedsScreen.this);
displayList();
}
public void displayList() {
dbHandler.getWritableDatabase();
dbHandler = new DatabaseHandler(this);
Cursor cursor = dbHandler.getData();
String from[] = new String[]{dbHandler.columnTitle};
int to[] = new int[]{R.id.textView1};
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to, 0);
ListView lv = getListView();
lv.setAdapter(dataAdapter);
}}
You should call getItemAtPosition(int position) from within your long-press listener. That will get you the Object from the collection that backs the ListView, in this case, the article from your RssReader that the user long-pressed upon. Sorta like:
...
db.open();
RssArticleThing fromList = (RssArticleThing) listItems.getItemAtPosition(position);
RssItem item = new RssItem();
item.title = fromList.title;
...
http://developer.android.com/reference/android/widget/AdapterView.html#getItemAtPosition(int)
I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}
I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);
Hey I'm trying to insert data in the SQLite database, but everytime I try to insert the logcat shows the error. THe error ir shown on a service that gets the calllog data and insert in the DB.
Error:
02-15 17:07:51.658: ERROR/AndroidRuntime(25392): java.lang.IllegalStateException: database not open
And the error is in this line of the Service class:
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
Here is the service:
public class TheService extends Service {
private static final String TAG = "TheService";
private static final String LOG_TAG = "TheService";
private Handler handler = new Handler();
private SQLiteDatabase db;
class TheContentObserver extends ContentObserver {
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
db = DataHandlerDB.createDB(this);
registerContentObservers();
}
#Override
public void onDestroy(){
db.close();
}
#Override
public void onStart(Intent intent, int startid) {
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
cursor.close();
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new TheContentObserver(handler));
}
}
And here is the DataHandlerDB Class:
public class DataHandlerDB {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table1";
protected static final String TABLE_NAME_2 = "table2";
protected String TAG = "DataHandlerDB";
//create the DB
public static SQLiteDatabase createDB(Context ctx) {
OpenHelper helper = new OpenHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
helper.onOpen(db);
db.close();
return db;
}
public static class OpenHelper extends SQLiteOpenHelper {
private final Context mContext;
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String[] sql = mContext.getString(R.string.ApplicationDatabase_OnCreate).split("\n");
db.beginTransaction();
try{
execMultipleSQL(db, sql);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e("Error creating tables and debug data", e.toString());
throw e;
} finally {
db.endTransaction();
}
}
private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
for(String s : sql){
if(s.trim().length() > 0){
db.execSQL(s);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*Log.w("Application Database",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);*/
}
#Override
public void onOpen(SQLiteDatabase db){
super.onOpen(db);
}
}
}
Don't you want this code
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
to be:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
?
Also, in the function
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
helper and db are local variables, not class members. This means that the database that you open here is not used for anything, anywhere.