I have an SQLite database that is populated when the user create a profile and fill a form with his contact informations in SetUpProfile activity and then retrieve that data and show it back on UserProfile activity.
Question: How to display the profile data (name, phone, address...) in textviews ?
This is what I've done so far:
Profile class
public class Profile {
private int _id = 1;
private String _industryName;
private String _industryType;
private String _email;
private String _phone;
private String _address;
private String _packageType;
public Profile() {
/** stays empty */
}
public Profile(int _id, String _industryName, String _industryType, String _email, String _phone, String _address, String _packageType) {
this._id = _id;
this._industryName = _industryName;
this._industryType = _industryType;
this._email = _email;
this._phone = _phone;
this._address = _address;
this._packageType = _packageType;
}
public Profile(String _industryName, String _industryType, String _email, String _phone, String _address, String _packageType) {
this._industryName = _industryName;
this._industryType = _industryType;
this._email = _email;
this._phone = _phone;
this._address = _address;
this._packageType = _packageType;
}
//getters and setters
}
This is the handler DBHandler class
addProfile() method:
public void addProfile(Profile profile) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_INDUSTRY_NAME, profile.get_industryName());
values.put(KEY_INDUSTRY_TYPE, profile.get_industryType());
values.put(KEY_EMAIL, profile.get_email());
values.put(KEY_PHONE, profile.get_phone());
values.put(KEY_ADDRESS, profile.get_address());
values.put(KEY_PACKAGE_TYPE, profile.get_packageType());
// Inserting Row
db.insert(TABLE_PROFILE, null, values);
db.close();
}
getProfile() method
public Profile getProfile(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PROFILE, new String[] {
KEY_ID, KEY_INDUSTRY_NAME, KEY_INDUSTRY_TYPE, KEY_EMAIL, KEY_PHONE, KEY_ADDRESS, KEY_PACKAGE_TYPE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Profile profile = new Profile(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6)
);
return profile;
}
MainActivity class
public class UserProfile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
//SQLite databes is supposed to populate those textViews
industry_type = (TextView) findViewById(R.id.b_industry);
b_name = (TextView) findViewById(R.id.b_industry_name);
b_email = (TextView) findViewById(R.id.mail);
b_phone = (TextView) findViewById(R.id.phone);
b_address = (TextView) findViewById(R.id.address);
plan_type = (TextView) findViewById(R.id.p_title);
edit_profile = (Button) findViewById(R.id.editProfile);
industry_img = (ImageView) findViewById(R.id.thumbnail);
plan_img = (ImageView) findViewById(R.id.plan_icon);
edit_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditProfile();
}
});
}
This is the approach I used :
SQLiteDatabase db = null;
DBHandler dd = new DBHandler(getBaseContext());
dd.getWritableDatabase();
db= openOrCreateDatabase("profileManager.db", Context.MODE_PRIVATE, null);
Cursor cc = db.rawQuery("SELECT * FROM profile", null);
if(cc.getCount()>=1) {
cc.moveToFirst();
try {
for(int i=0;i < cc.getCount();i++){
bname = cc.getString(1);
btype = cc.getString(2);
bmail = cc.getString(3);
bphone = cc.getString(4);
baddress = cc.getString(5);
bpackage = cc.getString(6);
}
}catch (Exception e){
e.getMessage();
}
}
You need to create getters of your private variables of profile class. For example as below.
public String getIndustryName() {
return _industryName;
}
Then you need to call getProfile() method from your activity class which return Profile object.
From Profile object, you can get all value and set it into relevent TextView and display. For example as below.
b_name.setText(profile.getIndustryName());
Related
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));
I have an app that uses a foreign key when updating a table. I want to be able to put their email down instead of using their number.
Here is the Database methods:
private int getIdFromName(String email) {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Integer> refs = new ArrayList<>();
Cursor cursor;
cursor = db.rawQuery("select " + REFEREE_EMAIL_COL + " from " +
REF_TABLE + " where " + REFEREE_EMAIL_COL + "='" + email + "'", null);
while (cursor.moveToNext()){
refs.add(cursor.getInt(0));
}
return refs.get(0);
}
public boolean updateRef(String email)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
int ref_id = getIdFromName(email);
values.put(REFEREE_ID_COL, ref_id);
db.insert(MATCH_TABLE, null, values);
return true;
}
Here is where I call it:
public class UpdateMatchActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnSave,btnDelete;
private EditText homeTeamEdit, awayTeamEdit, typeOfMatchEdit, redCardsEdit, bookingsEdit, groundEdit, refEdit, dateEdit, timeEdit,
awayScoreEdit, homeScoreEdit;
DBHandler mDatabaseHelper;
private String homeTeam, awayTeam, homeScore, awayScore;
private String typeOfMatch;
private String ref;
private String redCards, bookings;
private String date, time;
private String ground;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_match);
btnSave = (Button) findViewById(R.id.UpdateMatchButton);
homeTeamEdit = (EditText) findViewById(R.id.HomeTeamUpdate);
homeScoreEdit = (EditText) findViewById(R.id.updateHomeScore);
awayTeamEdit = (EditText) findViewById(R.id.AwayTeamUpdate);
awayScoreEdit = (EditText) findViewById(R.id.updateAwayScore);
typeOfMatchEdit = (EditText) findViewById(R.id.updateTypeOfMatch);
refEdit = (EditText) findViewById(R.id.updateRef);
groundEdit = (EditText) findViewById(R.id.updateGround);
refEdit = (EditText) findViewById(R.id.updateRef);
ref = refEdit.getText().toString();
mDatabaseHelper = new DBHandler(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
homeTeam = receivedIntent.getStringExtra("homeTeam");
homeScore = receivedIntent.getStringExtra("homeScore");
awayTeam = receivedIntent.getStringExtra("awayTeam");
awayScore = receivedIntent.getStringExtra("awayScore");
ground = receivedIntent.getStringExtra("ground");
typeOfMatch = receivedIntent.getStringExtra("typeOfMatch");
//set the text to show the current selected name
homeTeamEdit.setText(homeTeam);
awayTeamEdit.setText(awayTeam);
typeOfMatchEdit.setText(typeOfMatch);
groundEdit.setText(ground);
homeScoreEdit.setText(homeScore);
awayScoreEdit.setText(awayScore);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = refEdit.getText().toString();
if(!mDatabaseHelper.checkIfRefExists(ref)) {
mDatabaseHelper.updateRef(ref);
toastMessage("Ref Updated");
}
else
{
toastMessage("No ref with that email");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
I tried using the getIdFromName method when creating for the first time and it works but when I try update it, it gives me "java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)"
Totally lost here so any guidance would be appreciated.
I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..
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 have a SQLite Database of Web site data (ftp address, username, password, port, homedir, url etc). I can add records to the table but can't seem to update them.
I created a SiteManager Activity that loads each row and creates a WebSite object from each row. The WebSite's properties are loaded into EditTexts. The person can edit the properties and than the Update button SHOULD update the table row but it doesn't. Logcat doesn't give any errors so I'm completely at a loss, not sure where to start.
public class SiteManager extends Activity {
private DBAdapter myDb;
private EditText siteManFTPAddress;
private EditText siteManFTPUsername;
private EditText siteManFTPPassword;
private EditText siteManFTPPort;
private EditText siteManURL;
private EditText siteManHome;
private ImageView favIcon;
public ListView site_list;
private Button openBtn;
private Button siteManUpdateBtn;
private int _rowId;
private String _name;
private String _remoteHomeDir;
private int _isLive;
private String _address;
private String _username;
private String _password;
private int _port;
private String _url;
private boolean _status = false;
private String siteFolder;
private List<WebSite> model = new ArrayList<WebSite>();
private ArrayAdapter<WebSite> 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);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
siteManFTPAddress = (EditText) findViewById(R.id.siteManFTPAdd);
siteManFTPUsername = (EditText) findViewById(R.id.siteManFTPUser);
siteManFTPPassword = (EditText) findViewById(R.id.siteManFTPPass);
siteManFTPPort = (EditText) findViewById(R.id.siteManFTPPort);
siteManURL = (EditText) findViewById(R.id.siteManURL);
siteManHome = (EditText) findViewById(R.id.siteManHome);
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
File rootDir = new File(Environment
.getExternalStorageDirectory() + "/My Webs");
final WebSite item = (WebSite) parent
.getItemAtPosition(position);
_name = item.getName();
siteFolder = rootDir.toString() + "/" + _name;
_remoteHomeDir = item.getHomeDir();
_isLive = item.isLive();
String tmpaddress = item.getAddress();
_address = tmpaddress;
siteManFTPAddress.setText(_address);
String tmpuser = item.getUsername();
_username = tmpuser;
siteManFTPUsername.setText(_username);
String tmppass = item.getPassword();
_password = tmppass;
siteManFTPPassword.setText(_password);
int tmpport = item.getPort();
_port = tmpport;
String portString = Integer.toString(tmpport);
siteManFTPPort.setText(portString);
String tmpURL = item.getUrl();
_url = tmpURL;
siteManURL.setText(_url);
String tmpHome = item.getHomeDir();
_remoteHomeDir = tmpHome;
siteManURL.setText(_remoteHomeDir);
}
});
openBtn = (Button) findViewById(R.id.openSiteBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("siteopen", "siteopen");
returnResult.putExtra("sitename", _name);
returnResult.putExtra("sitehome", siteFolder);
returnResult.putExtra("sitelive", _isLive);
returnResult.putExtra("siteremotehome", _remoteHomeDir);
returnResult.putExtra("siteaddress", _address);
returnResult.putExtra("siteusername", _username);
returnResult.putExtra("sitepassword", _password);
returnResult.putExtra("siteport", _port);
returnResult.putExtra("url", _url);
setResult(2, returnResult);
finish();
}
});
siteManUpdateBtn = (Button)findViewById(R.id.siteManFTPUpdate);
siteManUpdateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_address = siteManFTPAddress.getText().toString();
_username = siteManFTPUsername.getText().toString();
_password = siteManFTPPassword.getText().toString();
String port = siteManFTPPort.getText().toString();
_port = Integer.parseInt(port);
Toast.makeText(SiteManager.this, "Update", Toast.LENGTH_LONG).show();
myDb.updateRow(_rowId, _name, _name, _isLive, _address, _username, _password, _port, _url);
model.clear();
adapter.notifyDataSetChanged();
displayRecords();
}
});
}
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) {
if (c.moveToFirst()) {
do {
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
int keyHomeIndex = c.getColumnIndex(DBAdapter.KEY_HOME);
_remoteHomeDir = c.getString(keyHomeIndex);
int keyLiveIndex = c.getColumnIndex(DBAdapter.KEY_LIVE);
_isLive = c.getInt(keyLiveIndex);
int keyAddressIndex = c.getColumnIndex(DBAdapter.KEY_ADDRESS);
_address = c.getString(keyAddressIndex);
int keyUsernameIndex = c.getColumnIndex(DBAdapter.KEY_USERNAME);
_username = c.getString(keyUsernameIndex);
int keyPassIndex = c.getColumnIndex(DBAdapter.KEY_PASSWORD);
_password = c.getString(keyPassIndex);
int keyPortIndex = c.getColumnIndex(DBAdapter.KEY_PORT);
_port = c.getInt(keyPortIndex);
int keyUrlIndex = c.getColumnIndexOrThrow(DBAdapter.KEY_URL);
_url = c.getString(keyUrlIndex);
WebSite sitesFromDB = new WebSite(_rowId, _name, _remoteHomeDir,
_isLive, _address, _username, _password, _port, _url);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
if(adapter.isEmpty()){
}
} while (c.moveToNext());
}
c.close();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
adapter.notifyDataSetChanged();
}
class SiteAdapter extends ArrayAdapter<WebSite> {
private final List<WebSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<WebSite> objects) {
super(context, R.id.sitename, 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.sitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
DBAdapter.java
public boolean updateRow(long rowId, String name, String homedir,
int islive, String address, String username, String password,
int port, String url) {
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_HOME, homedir);
newValues.put(KEY_LIVE, islive);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_URL, url);
// newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
The value _rowId is only ever set inside the displayRecordSet method where you iterate through the results from the database and set the _rowId:
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
This piece of code seems rather random to me. First you get the columnIndex for the rowId, next you get the index for this specific row and then you get the value of the column with index rowId and then set the _rowId field from this value.
I couldn't tell if the SQLite Database would be so nasty as to just return 0 if there isn't any value in the specified column, but that could definately be the problem.
So every time you get the _rowId set, it might just be set to 0 and when you try to update a row where rowId = 0 nothing happens, as no index in the database can be 0.
See the official documentation about getInt(columnIndex).
To diagnose issues like this, I usually add debug logs into the app. You can see these in your logcat. Log.d("tag", "there is something happening here: " + value);