Code
public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new ContactsAdapter(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
This displays all the contacts in the users phone in an activity... How do i move the data into a table in SQLite?
Progress so far:
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
Helper
public class ContactsHelper {
private String Name;
private String PhoneNumber;
public ContactsHelper() {
}
public ContactsHelper(String Name, String PhoneNumber) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
}
I've got to this point but I don't know how to proceed because I have so far only worked with adding/modifying data by clicking a button or similar to that.
How do I move the complete data to SQLite and when new contact is added obviously it wont get added to table automatically so when I add a feature like swipe to refresh I want the new contact to be added to the data as well?
Solution:
Add this method in your DatabaseHelper class:
public void insertData(String contactName, String phoneNumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
then, Firstly, make DatabaseHelper global object in your SettingsContacts class:
public DatabaseHelper database;
Add this in youronCreate()
database = new DatabaseHelper(SettingsContacts.this);
then after this, add the below line in addDataToList() method as shown:
Add this line:
database.insertData(name, phoneNumber)
as shown in below code (Write Here):
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
....... (Write Here)
}
}
That's it.
Hope it works.
To see if the data is already inserted, you can check the count of your table:
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHandler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Write the above method in you Database Handler class.
Then, in your activity after calling insertData(..), you can write like:
int count = database.getCount();
Log.e("Count From DB: ", String.valueOf(count));
Related
I'm making an Android Note Taking app, which save a note and display it in list of notes. if you touch each note it show a title and details of it in another layout. i can save note and i can show them in list but my problem is when i try to use intent to show that specific note's title and details.
what is do is use intent.putExtra("ID",...) and get that intent and show the note's detail and title with use of its ID. but i get "android.database.CursorIndexOutOfBoundsException" error and app crash.
this is part of my Note class:
public class Note {
private String Title, Content, Date, Time;
private long ID;
Note(){}
Note(String Title,String Content,String Date,String Time){
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
Note(long ID,String Title,String Content,String Date,String Time) {
this.ID = ID;
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
this is my NoteDataBase:
public class NoteDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
//column name for database tables
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public NoteDataBase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//create table
String query = "CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ID + " INT PRIMARY KEY," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion >= newVersion) {
return;
} else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long addNote(Note note) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
long ID = db.insert(DATABASE_TABLE,"null",c);
//c.put(KEY_ID,ID);
Log.d("Inserted", "addNote: note with id number " + KEY_ID + " has been inserted");
return ID;
}
public Note getNote(long ID){
//Select * from DatabaseTable where id = 1
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor != null)
cursor.moveToFirst();
return new Note(cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4));
}
public List<Note> getNotes() {
SQLiteDatabase db = getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
// Select * from databaseTable
String query = "SELECT * FROM "+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
}
this is my DetailActivity :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
Long id = intent.getLongExtra("ID",0);
NoteDataBase db = new NoteDataBase(this);
Note note = db.getNote(id);
Toast.makeText(this, "Title is "+ note.getTitle(), Toast.LENGTH_SHORT).show();
my error is in lines of both my Intent in DetailActivity and getNote method of NoteDataBase.
By defining the column id of your table as:
INT PRIMARY KEY
it is not defined as AUTOINCREMENT, so in every row that you add to the table, the column id is null, because you don't provide any value for it.
The value that is returned by the method addNote(), when you insert a new row, is the value of the column rowid and not the column id.
You must define the column as:
INTEGER PRIMARY KEY
You can also add AUTOINCREMENT in the above definition, if you don't want any deleted ids to be reused.
After you make this change you must uninstall the app from the device, so that the db is deleted and rerun to recreate the db and the table.
Also in the method getNote(), first check with moveToFirst() if the query returned any row:
public Note getNote(long ID){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor.moveToFirst())
return new Note(
cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4)
);
else return null;
}
I have 3 classes: MainActivity, DBHelper (extended SQLiteOpenHelper) and Student class.
In DBHelper I have methods like: addNewStudent, deleteStudent, findStudent and getAllStudents.
The method "getAllStudents" return arrayList and I want to show elements of this one in the listView on the mainactivity layou but I have problem with parameter of the ArrayList.
I tried on String just to understand using ArrayAdapter:
MAIN ACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
editTextID = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
listViewStudents = (ListView) findViewById(R.id.listViewStudents);
mDBStudents = new DBhelper(this);
// ------> this one provisional works:
final ArrayList<String> namesArray = new ArrayList<String>();
namesArray.add("Hania");
namesArray.add("Kasia");
final ArrayAdapter<String> namesAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,namesArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
namesArray.add(editTextName.getText().toString());
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(namesAdapter);
// ------> this one using <object> parameter in the ArrayList doesn't work and my app is stopped. I tried with Log.d but how to do it correctly with objects...
final ArrayList<Student> studentArray = new ArrayList<Student>();
Student s1 = new Student(1, "Natalia");
studentArray.add(s1);
final ArrayAdapter<Student> studentAdapter = new ArrayAdapter<Student>(MainActivity.this, android.R.layout.simple_list_item_1, studentArray);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Student s2 = new Student(Integer.parseInt(editTextID.getText().toString()), editTextName.getText().toString());
studentArray.add(s2);
mDBStudents.addNewStudent(editTextName.getText().toString());
listViewStudents.setAdapter(studentAdapter);
I want to show elements from the ArrayList which I add when I click "addStudentButton" in the ListView. Later I want t open the new Intent when I click on one positon from the listView. Do you have any suggestions what is the best way for beginner user of android?
On some pages are info about using ArrayAdapter, Cursor etc. but they aren't so clarity for me
DBhelper class
public class DBhelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "student";
public static final String COLUMN_ID = "studentID";
public static final String COLUMN_NAME = "studentName";
//initialize the database
public DBhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public int addNewStudent(String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,studentName);
return (int) db.insert(TABLE_NAME,null, values); //???
}
public ArrayList<Student> getAllStudents() {
ArrayList<Student> result = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
result.add(
new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
)
);
}
csr.close();
db.close();
return result;
}
public Student findStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)
)
);
}
csr.close();
db.close();
return result;
}
public Student deleteStudent(int studentID) {
Student result = null;
String whereclause = COLUMN_ID + "=?";
String[] whereargs = new String[]{String.valueOf(studentID)};
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME, null, whereclause, whereargs, null, null, null);
if (csr.moveToFirst()) {
result = new Student(
csr.getInt(csr.getColumnIndex(COLUMN_ID)), csr.getString(csr.getColumnIndex(COLUMN_NAME)));
db.delete(TABLE_NAME, whereclause, whereargs);
}
csr.close();
db.close();
return result;
}
public boolean updateStudent(int studentID, String studentName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COLUMN_ID, studentID);
args.put(COLUMN_NAME, studentName);
return db.update(TABLE_NAME, args, COLUMN_ID + "=" + ID, null) > 0;
}
}
Student class
public class Student {
private int studentID;
private String studentName;
public Student(int id, String studentName) { //konstruktor
this.studentID = id;
this.studentName = studentName;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
i need to make custom layout for my list view where data source is a sqlite database
when i run this code my output Thus shows (name next to phone) but i need to display output like this (phone under
name)
this is my code
here public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
List<Todo> todos;
MyDataBase db = new MyDataBase(this);
String m,m1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
final EditText editText1 = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button);
ListView listView = (ListView) findViewById(R.id.listView);
todos = db.getallcontacts();
final ArrayAdapter adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,todos);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m = editText.getText().toString();
m1 = editText1.getText().toString();
db.AddnewContact(new Todo(m, m1));
adapter.add(new Todo(m, m1));
Toast.makeText(getApplicationContext(), "contact saved", Toast.LENGTH_LONG).show();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long rowId) {
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setMessage("you need to delete this contact");
adb.setPositiveButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Todo td = todos.get(position);
db.deleteContact(td);
adapter.remove(td);
}
});
adb.show();
adapter.notifyDataSetChanged();
}
});
listView.setAdapter(adapter);
}
my database calss
here public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
final String KEY_NAME = "name";
final String KEY_PH_NO = "phone_number";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void AddnewContact (Todo todo)// this method to add new contact
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME,todo.getName());
values.put(KEY_PH_NO, todo.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public Todo getContact(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO },KEY_ID + "=?",new String[] { String.valueOf(id) },null,null,null,null);
cursor.moveToFirst();
Todo contact = new Todo(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
public List<Todo> getallcontacts()
{
List<Todo> contactList = new ArrayList<Todo>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Todo contact = new Todo();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
public void deleteContact(Todo contact) {
int id = contact.getID();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID
+ " = " + id, null);
db.close();
}
public Cursor fetchAllCountries() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor mCursor = database.query(TABLE_CONTACTS, new String[] {KEY_ID,
KEY_NAME,KEY_PH_NO},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
my todo calss
`enter public class Todo {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Todo(){
}
// constructor
public Todo(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Todo(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
#Override
public String toString() {
return _name+" "+_phone_number;
}
}
`
I was tried to insert some values to my SQLite database. like(id,name,number and image).but i got a null pointer exception while run the code. the values is display in the pojo class while i print using sys out. i dont know what is the problem here. please help me. Thanks in advance.
my code is here
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
picture = data.get(position);
listModelData.setTitle(String.valueOf(a[position]));
listModelData.setImageUrl(picture._image);
listModelData.setitemName(itemname);
listData.add(listModelData);
((MainActivity) context).getData(listData);
}
});
/////////////////////////////////////////////
public class MainActivity extends Activity {
ArrayList<ListModel> listData = new ArrayList<ListModel>();
HorizontalListView listview;
// HorizontalAdapter hAdapter;
HorizantalDBHandler hdb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (HorizontalListView) findViewById(R.id.listview);
// hAdapter = new HorizontalAdapter(getApplicationContext(), listData);
// listview.setAdapter(hAdapter);
}
public void getData(ArrayList<ListModel> listData) {
// TODO Auto-generated method stub
System.out.println("########DDDDDDDDD##########");
int id = 301;
String value = listData.get(0).getTitle();
String itemname = listData.get(0).getitemName();
byte[] image = listData.get(0).getImageUrl();
System.out.println(value);
System.out.println(image);
System.out.println(itemname);
System.out.println(id);
hdb.addContact(new HorizantalPojo(id, itemname, value, image));
System.out.println(value);
System.out.println(image);
System.out.println(itemname);
// hAdapter = new HorizontalAdapter(getApplicationContext(),listData);
// listview.setAdapter(hAdapter);
// hAdapter.notifyDataSetChanged();
}
}
///////////////////////////////////////////////////
public class HorizantalPojo {
// private variables
int _id;
public String _name;
public byte[] _image;
String _number;
// Empty constructor
public HorizantalPojo() {
}
// constructor
public HorizantalPojo(int id, String number, String name, byte[] image) {
System.out.println("it comessssssssss");
this._name = name;
this._image = image;
this._number = number;
this._id = id;
System.out.println(_id);
System.out.println(_name);
System.out.println(_image);
System.out.println(_number);
System.out.println("it comessssssssss");
}
// constructor
public HorizantalPojo(String name, byte[] image) {
this._name = name;
this._image = image;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting name
public String getName() {
return this._name;
}
// setting name
public void setName(String name) {
this._name = name;
}
// getting phone number
public byte[] getImage() {
return this._image;
}
// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
public String getNumber() {
return this._number;
}
// setting phone number
public void setNumber(String number) {
this._number = number;
}
}
/////////////////////////////////////////////////////
public class HorizantalDBHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "hrlist";
// Contacts table name
// private static final String TABLE_CONTACTS = "breakfast";
private static final String TABLE_BREAKFAST = "hrlist";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NUMBER = "number";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
public HorizantalDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_BREAKFAST_TABLE = "CREATE TABLE " + TABLE_BREAKFAST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_NUMBER + " TEXT," + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_BREAKFAST_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BREAKFAST);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public// Adding new contact
void addContact(HorizantalPojo contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
System.out.println("################");
System.out.println("################");
System.out.println("################");
System.out.println(contact._id);
System.out.println(contact._name);
System.out.println(contact._number);
System.out.println(contact._image);
values.put(KEY_ID, contact._id);
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_NUMBER, contact._number);
values.put(KEY_IMAGE, contact._image); // Contact Phone
//
//
// Inserting Row
db.insert(TABLE_BREAKFAST, null, values);
db.close(); // Closing database connection
}
// // Getting All Contacts
public List<HorizantalPojo> getAllContacts() {
List<HorizantalPojo> contactList = new ArrayList<HorizantalPojo>();
// Select All Query
String selectQuery = "SELECT * FROM hrlist ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HorizantalPojo contact = new HorizantalPojo();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// contact.setNumber(cursor.getString(3));
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println(cursor.getString(1));
System.out.println(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;
}
}
Your hdb=null
hdb=new HorizantalDBHandler(MainActivity.this);
initialized it before used. As seen your code.
hdb object of HorizantalDBHandler is null.
Initialize it before calling addContact method:
hdb=new HorizantalDBHandler(MainActivity.this);
hdb.addContact(new HorizantalPojo(id, itemname, value, image));
I'm building a note taking app in Android. I have developed insertion of the note in the app right now which I have done through SQLite database. Now I want to delete the particular note from the SQLite database through the context menu. When user long presses any record in the app it will through a context menu with "Delete" option. Now, My problem is I'm able to remove item from listview but it's not getting deleted from database.
Here's my code:
MainActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
int position;
super.onContextItemSelected(item);
if(item.getTitle().equals("Delete")) {
//Add code
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
position = (int)info.id;
//Notes note_id = (Notes)adapter.getNote(info.position);
db.deleteNote(new Notes(position));
list.remove(position);
this.adapter.notifyDataSetChanged();
}
return true;
};
DatabaseHandler.java:
package com.amitmerchant.notesapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notesManager";
private static final String TABLE_NOTES = "notes";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note";
private static final String KEY_DATE = "date_added";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NOTES+"("+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NOTE+" TEXT,"+KEY_DATE+" DATE"+")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote()); // Contact Name
// Inserting Row
db.insert(TABLE_NOTES, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Notes getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_NOTE, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Notes note = new Notes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return note;
}
// Getting All Contacts
public List<Notes> getAllNotes() {
List<Notes> noteList = new ArrayList<Notes>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Notes note = new Notes();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setNote(cursor.getString(1));
// Adding contact to list
noteList.add(note);
} while (cursor.moveToNext());
}
// return contact list
return noteList;
}
// Getting contacts Count
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
}
// Deleting single contact
public void deleteNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
db.close();
}
}
Notes.java
package com.amitmerchant.notesapp;
public class Notes {
// private variables
int _id;
String _note;
String _note_date;
// Empty constructor
public Notes() {
}
public Notes(int id, String _note) {
this._id = id;
this._note = _note;
}
public Notes(String _note) {
this._note = _note;
}
public Notes(int id) {
this._id = id;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getNote() {
return this._note;
}
public void setNote(String note) {
this._note = note;
}
}
Guys, what am I doing wrong here? Please correct me. Thanks!