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());
}
Related
I am trying to create a quiz app where a category can be selected by clicking on a listView item. Each category has code like 0,1,2. For football, it is 0. After clicking on the football item, the app keeps on going to the home screen instead of logging the data I want. Please help me with the error.
Quiz Category Selection Class
String quizCategory = intent.getStringExtra("QuizCategory");
//Deciding which database to Open and choose
switch (quizCategory) {
case "0":
Log.i("Category", "Football");
Football football = new Football(this);
football.createDatabase();
football.openDatabase();
football.getWritableDatabase();
long x=football.getRowCount();
break;
default:
Log.i("Message", "Error");
}
}
Football Class
public class Football extends SQLiteOpenHelper {
private static final String Database_path = "/data/data/com.google.quiz/databases/";
private static final String Database_name = "football.db";
private static Context context;
private static final int version = 1;
public SQLiteDatabase sqlite;
public Football(Context context) {
super(context, Database_name, null, version);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbexist = DBexists();
if (!dbexist) {
this.getReadableDatabase();
copyDBfromResource();
}
}
private void copyDBfromResource() {
InputStream is;
OutputStream os;
String filePath = Database_path + Database_name;
try {
is = context.getAssets().open(Database_name);//reading purpose
os = new FileOutputStream(filePath);//writing purpose
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//writing to file
}
os.flush();//flush the outputstream
is.close();//close the inputstream
os.close();//close the outputstream
} catch (IOException e) {
throw new Error("Problem copying database file:");
}
}
public void openDatabase() throws SQLException {
String myPath = Database_path + Database_name;
sqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean DBexists() {
SQLiteDatabase db = null;
try {
String databasePath = Database_path + Database_name;
db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
} catch (SQLException e) {
Log.e("Sqlite", "Database not found");
}
if (db != null)
db.close();///close the opened file
return db != null ? true : false;
}
public long getRowCount() {
SQLiteDatabase db = this.getReadableDatabase();
long x = DatabaseUtils.queryNumEntries(db, "football");
db.close();
return x;
}
}
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.
I have been building a simple note app and have successfully SQlite database and loaders to load data on a listview. Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how. I've search but mainly tutorials are for Content provider, I read this: http://developer.android.com/reference/android/content/AsyncTaskLoader.html#q=addAll
but not understand much because they use BroadcastReceiver to get change on sd card.
Im all ears to any suggestion and thanks for any help in advance!
this is my code: WhiteNote.java
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
noteListAdapter=new NoteListAdapter(context, new ArrayList<NoteItems>());
note_database.open();
getLoaderManager().initLoader(0, null,WhiteNote.this);
note_database.close();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.dbnoteListAdapter);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context,note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context, data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_noteitems= new ArrayList<NoteItems>();
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
loader_db = db;
loader_noteitems=loader_db.get_NoteListArray(loader_noteitems,loader_db);
}
#Override
protected void onStartLoading() {
if (loader_noteitems != null) {
deliverResult(loader_noteitems); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open();
ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
loader_db.get_NoteListArray(note_items,loader_db);
loader_db.close();
return note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
if (isReset()) {
if (data != null) {
onReleaseResources(data);
}
}
ArrayList<NoteItems> oldNotes = loader_noteitems;
loader_noteitems = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldNotes != null) {
onReleaseResources(oldNotes);
}
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_noteitems = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_noteitems = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
my NoteDatabase.java
public class NoteDatabase {
private static final String DATABASE_NAME = "DB_NOTE";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NOTE = "NOTE";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TOPIC = "Topic";
public static final String COLUMN_NOTECONTENT = "Content";
public static final String COLUMN_NAME = "Name";
public NoteListAdapter dbnoteListAdapter;
private static Context my_context;
static SQLiteDatabase note_sqldb;
private OpenHelper noteopenHelper;
public NoteDatabase(Context c){
NoteDatabase.my_context = c;
}
public NoteDatabase open() throws SQLException{
noteopenHelper = new OpenHelper(my_context);
note_sqldb = noteopenHelper.getWritableDatabase();
return this;
}
public void close(){
noteopenHelper.close();
}
public long createData(String chude_note, String noidung_note) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TOPIC, chude_note);
cv.put(COLUMN_NOTECONTENT, noidung_note);
cv.put(COLUMN_NAME, "by Black");
return note_sqldb.insert(TABLE_NOTE, null, cv);
}
public String getData() {
String[] columns = new String[] {COLUMN_ID,COLUMN_TOPIC,COLUMN_NOTECONTENT,COLUMN_NAME};
Cursor c = note_sqldb.query(TABLE_NOTE, columns, null, null, null, null, null);
/*if(c==null)
Log.v("Cursor", "C is NULL");*/
String result="";
int iRow = c.getColumnIndex(COLUMN_ID);
int iTopic = c.getColumnIndex(COLUMN_TOPIC);
int iContent = c.getColumnIndex(COLUMN_NOTECONTENT);
int iOwner = c.getColumnIndex(COLUMN_NAME);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result +" \n"+ c.getString(iRow)
+ "\n - Topic: " + c.getString(iTopic)
+ "\n - Content: " + c.getString(iContent)
+ "\n - Owner: " + c.getString(iOwner) + "\n";
}
c.close();
//Log.v("Result", result);
return result;
}
public Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (note_sqldb.isOpen()) {
note_sqldb.close();
}
note_sqldb = noteopenHelper.getWritableDatabase();
c1 = note_sqldb.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
public void get_NoteListAdapter() {
ArrayList<NoteItems> noteList = new ArrayList<NoteItems>();
noteList.clear();
open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteList.add(one_rowItems);
}
c1.close();
close();
dbnoteListAdapter = new NoteListAdapter(my_context, noteList);
}
public ArrayList<NoteItems> get_NoteListArray(ArrayList<NoteItems> noteitems_list,NoteDatabase db) {
noteitems_list.clear();
db.open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteitems_list.add(one_rowItems);
}
c1.close();
db.close();
return noteitems_list;
}
public int deleteNote(String topic) {
return note_sqldb.delete(TABLE_NOTE, COLUMN_TOPIC + "='" + topic + "'", null);
}
public int deleteAllNote() {
return note_sqldb.delete(TABLE_NOTE, null, null);
}
}
Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how.
There is no way to make that happen automatically. Either:
Something tells the loader that the data changed, so it knows to reload, or
The Loader is the one that is doing the "add, change, or delete a note in database"
I went with the latter approach with my CWAC-LoaderEx project and its SQLiteCursorLoader.
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.