Related
The project im working on allow the user to register and login and all works perfectly until I spotted something wrong with the code. It doesn't count as an error because the compiler don't think its an error. Its just a bug or whatever people call it is. So here's what happened . The user login to their account, the database transfer their data into intent extras. then on the next activities, the username, coins and gems appears on top of the page so that the user know how much coins they have left. For testing purpose, i added add coin and decrease coin button. still, the code works perfectly. But after the user log out and relogin, the coins backs to the original amount. I know the problem caused by putting a value on the coin variable in User.java class. And still while logging in I put the default value of coins and gems for the user in the intent extras. I just cant find my way on how to put the value from database to the intent extras while user logging in.
so heres the code for login activity
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check user input is correct or not
if (validate()) {
//Get values from EditText fields
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User player1 = new User(null, null, Email, Password);
//Authenticate user
User currentUser = myDb.Authenticate(player1);
//Check Authentication is successful or not
if (currentUser != null) {
System.out.println("Success");
Bundle extras = new Bundle();
extras.putString("P_ID", currentUser.getId());
extras.putString("P_NAME", currentUser.getName());
extras.putInt("P_COINS", currentUser.getCoins());
extras.putInt("P_GEMS", currentUser.getGems());
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
//User Logged in Failed
System.out.println("Failed");
}
}
}
});
the homeactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.home_screen);
myDb = new DatabaseHelper(this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
pid = extras.getString("P_ID");
pname = extras.getString("P_NAME");
pcoins = extras.getInt("P_COINS");
pgems = extras.getInt("P_GEMS");
nametxt = (TextView)findViewById(R.id.playernametext);
coinstxt = (TextView)findViewById(R.id.playercoinstext);
gemstxt = (TextView)findViewById(R.id.playergemstext);
addcoin = (Button)findViewById(R.id.addbtn);
decoin = (Button)findViewById(R.id.decbtn);
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
addcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins += 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
decoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins -= 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
}
and of course the user class
public class User {
public String id;
public String userName;
public String email;
public String password;
public int coins = 1000;
public int gems = 10;
public User(String id, String userName, String email, String password) {
this.id = id;
this.userName = userName;
this.email = email;
this.password = password;
}
public String getId() {
return this.id;
}
public String getName() {
return this.userName;
}
public void addCoins(int addAmount) {
this.coins = addAmount;
}
public void decCoins(int decAmount) {
this.coins = decAmount;
}
public int getCoins() {
return this.coins;
}
public void addGems(int addAmount) {
this.gems = addAmount;
}
public void decGems(int decAmount) {
this.gems = decAmount;
}
public int getGems() {
return this.gems;
}
}
Honestly, my brain lacks of logic. Thats why i come here, to see whether my code does make sense.
And please, if you don't understand what i mean, just ask me which parts and please just dont immediately flag my question. Im really bad at english, trust me.
I'd suggest only passing the userid (which should never change) and then always getting the values coins etc from the database and also only changing them in the database (followed by resetting the displayed values from the values in the database).
You would then not have the issue of trying to juggle two sets of data you would then rely on the real data i.e. that in the database.
Working Example
The following is some code that goes through the basics.
When it starts the MainActivity, immediately starts the LoginActivity when you login then it takes you to the HomeActivity. This display the current Userid, Username, coins (initially 0) and gems.
There are 2 buttons Add10Coins and Add10gems clicking them will apply the new values to the DB displaying the updated values. If you stop the App and rerun, login then the values will be as they were.
Passing values wise, although the LoginActivity sets 3 Intent Extra values only one is used (the userid as a long) by the HomeActivity, but as per the values display all are accessible. If another activity is started then all you have to do is pass the userid via the intent.
The code isn't what I'd call complex but I'd certainly suggest going through it and try to understand it.
user.java
I've added some methods and also added some Constants, this is now :-
public class User {
public static final int ADJUSTTYPE_ADD = 1;
public static final int ADJUSTTYPE_REPLACE = 2;
public static final int ADJUSTTYPE_MULTIPLY = 3;
public static final int ADJUSTTYPE_DIVIDE = 4;
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String userName) {
this.userName = userName;
}
public String getName() {
return this.userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getCoins() {
return this.coins;
}
public void setGems(int gems) {
this.gems = gems;
}
public int getGems() {
return this.gems;
}
public long getLongId() {
long id;
try {
id = Long.valueOf(this.id);
} catch (Exception e) {
return -1;
}
return id;
}
}
DatabaseHelper.java
This has been written from scratch based upon not the most stringent inspection of your code, it will largely be affected by my styling/usage techniques but not to the extent that I'd apply for real development.
Within this is the method adjustCoinsAndOrGems this is what is used to update the gems or coins in the DB and also in the returned User (so that a synchronised version of the User is returned, not that this returned use is used (I personally prefer to access the database as long as it's not an issue (e.g. noticeably affects performance)))
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mygame.db";
public static final int DBVERSION = 1;
public static final String TBL_USER = "user";
public static final String COL_USER_ID = BaseColumns._ID;
public static final String COL_USER_NAME = "user_name";
public static final String COL_USER_EMAIL = "user_email";
public static final String COL_USER_PASWWORD = "user_password";
public static final String COL_USER_COINS = "user_coins";
public static final String COL_USER_GEMS = "user_gems";
public static final String TBL_PLAYER = "player";
public static final String COL_PLYAER_ID = BaseColumns._ID;
public static final String COL_PLAYER_OWNINGUSER = "player_owninguser";
public static final String COL_PLAYER_NAME = "player_name";
//...... other columns
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_user = "CREATE TABLE IF NOT EXISTS " + TBL_USER + "(" +
COL_USER_ID + " INTEGER PRIMARY KEY," +
COL_USER_NAME + " TEXT NOT NULL UNIQUE," +
COL_USER_EMAIL + " TEXT NOT NULL UNIQUE," +
COL_USER_PASWWORD + " TEXT NOT NULL," +
COL_USER_COINS + " INTEGER," +
COL_USER_GEMS + " INTEGER" +
")";
String crt_tbl_player = "CREATE TABLE IF NOT EXISTS " + TBL_PLAYER + "(" +
COL_PLYAER_ID + " INTEGER PRIMARY KEY," +
COL_PLAYER_NAME + " TEXT NOT NULL," +
COL_PLAYER_OWNINGUSER + " INTEGER REFERENCES " + TBL_USER + "(" + COL_USER_ID + ")" +
")";
db.execSQL(crt_tbl_user);
db.execSQL(crt_tbl_player);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
/*
Note core add but not intended to be used directly
Note this assumes that checks are done to ensure that name, email and password
have been provided
*/
private long addUser(Long id, String name, String email, String password, int coins, int gems) {
ContentValues cv = new ContentValues();
if (id > 0) {
cv.put(COL_USER_ID,id);
}
if (name.length() > 0) {
cv.put(COL_USER_NAME,name);
}
if (email.length() > 0 ) {
cv.put(COL_USER_EMAIL,email);
}
if (password.length() > 0) {
cv.put(COL_USER_PASWWORD,password);
}
cv.put(COL_USER_COINS,coins);
cv.put(COL_USER_GEMS,gems);
if (cv.size() < 1) return -1; //<<<<<<<<<< return if nothing to add
return mDB.insert(TBL_USER,null,cv);
}
/*
For add with just name, email and password (normal usage)
*/
public long addUser(String name, String email, String password) {
return this.addUser(-1L,name,email,password,0,0);
}
/*
For adding a user setting the coins and gems (special usage)
*/
public long addUserSettingCoinsAndGems(String name, String email, String password, int coins, int gems) {
return this.addUser(-1L,name,email,password,coins,gems);
}
public User getUser(long id) {
User rv = new User("-1","",",",""); // Invalid user
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String userid) {
String whereclause = COL_USER_ID + "=?";
User rv = new User("-1","",",",""); // Invalid user
long id;
try {
id = Long.valueOf(userid);
} catch (Exception e) {
return rv;
}
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String email, String password) {
User rv = new User("-1","","","");
String whereclause = COL_USER_EMAIL + "=? AND " + COL_USER_PASWWORD + "=?";
String[] whereargs = new String[]{email,password};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId( String.valueOf(csr.getLong(csr.getColumnIndex(COL_USER_ID))));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User adjustCoinsAndOrGems(User u, int coins, int coin_adjustmode, int gems, int gem_adjustmode) {
ContentValues cv = new ContentValues();
User rv;
User user_fromDB = getUser(u.getId());
if (user_fromDB.id.equals("-1")) return u; // User not found so return
switch (coin_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_COINS,coins);
break;
case User.ADJUSTTYPE_ADD:
if (coins != 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() + coins);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() * coins);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() / coins);
}
break;
}
switch (gem_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_GEMS,gems);
break;
case User.ADJUSTTYPE_ADD:
if (gems != 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() + gems);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() * gems);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() / gems);
}
break;
}
if (cv.size() < 1) return u;
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{u.getId()};
mDB.update(TBL_USER,cv,whereclause,whereargs);
return getUser(user_fromDB.getId());
}
public boolean authenticateUser(String email, String password) {
User u = getUser(email,password);
return (u.getLongId() > 0);
}
}
MainActivity.java
Very simple activity that starts the LoginActivity and when finally returned to does nothing (so you might as well kill the app).
public class MainActivity extends AppCompatActivity {
TextView mMessage;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
mDB = new DatabaseHelper(this);
addSomeTestingUsers();
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
private void addSomeTestingUsers() {
if (DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(),DatabaseHelper.TBL_USER) > 0) return;
mDB.addUser("Fred","fred#fredmal.com","password");
mDB.addUser("Mary","mary#mary.email.com","password");
}
}
LoginActivity
This is pretty straightforward note that as it stands you have to Login and that the emails and passwords for the 2 users are coded in the MainActivity. When supplied correctly the HomeActivivty is started :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
public static final String INTENTKEY_STRINGUSERID = "IK_USERIDSTRING";
Button mloginbtn;
EditText mEmail,mPassword;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mEmail = this.findViewById(R.id.email);
mPassword = this.findViewById(R.id.password);
mDB = new DatabaseHelper(this);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleAuthentication();
}
});
}
private void handleAuthentication() {
if (mDB.authenticateUser(mEmail.getText().toString(),mPassword.getText().toString())) {
User u = mDB.getUser(mEmail.getText().toString(),mPassword.getText().toString());
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,u.getName());
i.putExtra(INTENTKEY_USERID,u.getLongId());
i.putExtra(INTENTKEY_STRINGUSERID,u.getId());
startActivity(i);
finish();
}
}
HomeActivity
For brevity, this has been used to display the coins and gems, it to is pretty basic and relies upon methods in the DatabaseHelper to do much of the work.
public class HomeActivity extends AppCompatActivity {
TextView mUserameTextView, mUseridTextView, mCoinsTextView, mGemsTextView;
Button mAdd10Coins, mAdd10Gems,mDone;
User mUser;
long mUserid;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = this;
mDB = new DatabaseHelper(mContext);
mUserameTextView = this.findViewById(R.id.username);
mUseridTextView = this.findViewById(R.id.userid);
mCoinsTextView = this.findViewById(R.id.coins);
mGemsTextView = this.findViewById(R.id.gems);
Intent i = this.getIntent();
mUserid = i.getLongExtra(LoginActivity.INTENTKEY_USERID,-1);
mUser = mDB.getUser(mUserid);
refreshDisplay();
initButtons();
}
private void initButtons() {
mAdd10Coins = this.findViewById(R.id.add10coins);
mAdd10Coins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,10,User.ADJUSTTYPE_ADD,0,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mAdd10Gems = this.findViewById(R.id.add10gems);
mAdd10Gems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,0, User.ADJUSTTYPE_ADD,10,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mDone = this.findViewById(R.id.done);
mDB = new DatabaseHelper(mContext);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
private void refreshDisplay() {
mUseridTextView.setText(mUser.getId());
mUserameTextView.setText(mUser.getName());
mCoinsTextView.setText(String.valueOf(mUser.getCoins()));
mGemsTextView.setText(String.valueOf(mUser.getGems()));
}
}
Yes I have read many many answers here on SO and tried all but nothing works for me. I dont know what is wrong because according to me everything looks good.
Many times I changed DB version,. Even I renamed db and table name but nothing works. I can print the log which shows the correct result but why it is not inserting into the database.
Also When I remove all the Checkbox fields from table then data insertion works.
A humble request..please do not block me from asking question as this question is asked many times by others and I tried all solutions but nothing worked.
Please guide me as I am completely new to Java and Android Studio.
Sometimes The Error is :
table tblCinFormNew has no column named chkbox_other
Sometimes The Error is :
table tblCinFormNew has no column named chkbox_cosmo
Here is my DatabaseHandler class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "dbCinExtDb";
private static final String TABLE_CONTACTS = "tblCinFormNew";
private static final String KEY_ID = "id";
private static final String KEY_EMAIL = "email";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_WORK_PH_NO = "work_phone_number";
private static final String KEY_FNAME = "fname";
private static final String KEY_LNAME = "lname";
private static final String KEY_ADDRESS = "address";
private static final String KEY_CITY = "city";
private static final String KEY_STATE = "state";
private static final String KEY_ZIP = "zip";
private static final String KEY_SALOON = "chkbox_saloon";
private static final String KEY_COSMO = "chkbox_cosmo";
private static final String KEY_STUDENT = "chkbox_student";
private static final String KEY_OTHER = "chkbox_other";
private static final String KEY_ADD_INFO = "chkbox_add_info";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = " CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_EMAIL + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_WORK_PH_NO + " TEXT, " + KEY_FNAME + " TEXT, "
+ KEY_LNAME + " TEXT," + KEY_ADDRESS + " TEXT,"+ KEY_CITY + " TEXT,"
+ KEY_STATE + " TEXT," + KEY_ZIP + " TEXT " + KEY_SALOON + " TEXT " + KEY_COSMO + " TEXT " + KEY_STUDENT
+ " TEXT " + KEY_OTHER + " TEXT " + KEY_ADD_INFO + " TEXT " + ")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);
//db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS_NEW);
// Create tables again
onCreate(db);
}
void addContactNew(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL, contact.getEmail());
values.put(KEY_PH_NO, contact.getPhone());
values.put(KEY_WORK_PH_NO, contact.getWorkPhone());
values.put(KEY_FNAME, contact.getFirstName()); // Contact Name
values.put(KEY_LNAME, contact.getlastName());
values.put(KEY_ADDRESS, contact.getAddress());
values.put(KEY_CITY, contact.getCity());
values.put(KEY_STATE, contact.getState());
values.put(KEY_ZIP, contact.getZip());
values.put(KEY_SALOON, contact.getSaloon());
values.put(KEY_COSMO, contact.getCosmo());
values.put(KEY_STUDENT, contact.getStudent());
values.put(KEY_OTHER, contact.getOther());
values.put(KEY_ADD_INFO, contact.getAddInfo());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}}
Here is my MainActivity.Java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHandler db = new DatabaseHandler(this);
final ProgressDialog progress = new ProgressDialog(this);
Button btn= (Button) findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText email = (EditText) findViewById(R.id.editTextEmail);
EditText phone = (EditText) findViewById(R.id.editTextPhone);
EditText work_phone = (EditText) findViewById(R.id.editTextPhone1);
EditText fname = (EditText) findViewById(R.id.editTextFirstName);
EditText lname = (EditText) findViewById(R.id.editTextLastName);
EditText address = (EditText) findViewById(R.id.editTextAddress);
EditText city = (EditText) findViewById(R.id.editTextCity);
EditText state = (EditText) findViewById(R.id.editTextState);
EditText zip = (EditText) findViewById(R.id.editTextZip);
CheckBox chkSaloon =(CheckBox) findViewById(R.id.checkBoxSalon);
CheckBox chkCosmo =(CheckBox) findViewById(R.id.checkBoxCosmetologist);
CheckBox chkStudent = (CheckBox) findViewById(R.id.checkBoxStudent);
CheckBox chkOther = (CheckBox) findViewById(R.id.checkBoxOther);
CheckBox chkAddInfo = (CheckBox)findViewById(R.id.checkBoxAdditionalInfo);
String _email=email.getText().toString();
String _phone=phone.getText().toString();
String _work_phone=work_phone.getText().toString();
String _fname=fname.getText().toString();
String _lname=lname.getText().toString();
String _address=address.getText().toString();
String _city=city.getText().toString();
String _state=state.getText().toString();
String _zip=zip.getText().toString();
String strSaloon;
String strCosmo;
String strStudent;
String strOther;
String strAdInfo;
if(chkSaloon.isChecked()) {
strSaloon="Salon owner";
}
else{
strSaloon="Not Checked";
}
if(chkCosmo.isChecked()) {
strCosmo="Licensed Cosmetologist";
}
else{
strCosmo="Not Checked";
}
if(chkStudent.isChecked()) {
strStudent="Student";
}
else{
strStudent="Not Checked";
}
if(chkOther.isChecked()) {
strOther="Other";
}
else{
strOther="Not Checked";
}
if(chkAddInfo.isChecked()) {
strAdInfo="Please send me additional information";
}
else{
strAdInfo="Not Checked";
}
Log.d("Insert: ", "Inserting ..");
db.addContactNew(new Contact(_email,_phone,_work_phone,_fname,_lname,_address,_city,_state,_zip,
strSaloon,strCosmo,strStudent,strOther,strAdInfo));
// Reading all contacts
Log.d("Reading Email",_email);
Log.d("Reading Phone",_phone);
Log.d("Reading Work Phone",_work_phone);
Log.d("Reading Fname",_fname);
Log.d("Reading Lname",_lname);
Log.d("Reading Address",_address);
Log.d("Reading City",_city);
Log.d("Reading State",_state);
Log.d("Reading Zip",_zip);
Log.d("Reading Saloon",strSaloon);
Log.d("Reading Cosmo",strCosmo);
Log.d("Reading Student",strStudent);
Log.d("Reading Other",strOther);
Log.d("Reading AddInfo",strAdInfo);
// Log.d("GetContactCount",String.valueOf(db.getContactsCount()));
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID() +" ,Name: " + cn.getFirstName() + cn.getFirstName() + " ,Saloon: " + cn.getSaloon()
+ " ,Cosmo: " + cn.getCosmo();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
});
}
}
Here is my Contact.java Constructor
public class Contact {
int id;
String email;
String phone;
String workPhone;
String firstName;
String lastName;
String address;
String city;
String state;
String zip;
String chkSalon;
String chkCosmo;
String chkStudent;
String chkOther;
String chkAddInfo;
public Contact()
{
// Empty Constructor
}
public Contact(int id, String email, String phone, String workPhone,String firstName,
String lastName, String address,String city , String state,String zip, String chkSalon,
String chkCosmo, String chkStudent, String chkOther,String chkAddInfo
){
this.id = id;
this.email = email;
this.phone = phone;
this.workPhone=workPhone;
this.firstName=firstName;
this.lastName=lastName;
this.address=address;
this.city=city;
this.state=state;
this.zip=zip;
this.chkSalon=chkSalon;
this.chkCosmo=chkCosmo;
this.chkStudent=chkStudent;
this.chkOther=chkOther;
this.chkAddInfo=chkAddInfo;
}
// constructor
public Contact(String email, String phone, String workPhone,String firstName,
String lastName, String address,String city , String state,String zip, String chkSalon,
String chkCosmo, String chkStudent, String chkOther,String chkAddInfo
){
this.email = email;
this.phone = phone;
this.workPhone=workPhone;
this.firstName=firstName;
this.lastName=lastName;
this.address=address;
this.city=city;
this.state=state;
this.zip=zip;
this.chkSalon=chkSalon;
this.chkCosmo=chkCosmo;
this.chkStudent=chkStudent;
this.chkOther=chkOther;
this.chkAddInfo=chkAddInfo;
}
// getting ID
public int getID(){
return this.id;
}
// setting id
public void setID(int id){
this.id = id;
}
public String getPhone(){
return this.phone;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getWorkPhone(){
return this.workPhone;
}
public void setWorkPhone(String workPhone){
this.workPhone = workPhone;
}
public String getEmail(){
return this.email ;
}
public void setEmail(String email){
this.email = email;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName=firstName;
}
public String getlastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName=lastName;
}
public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return this.address;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city=city;
}
public String getState(){
return this.state;
}
public void setState(String state){
this.state=state;
}
public String getZip(){ return this.zip; }
public void setZip(String zip){
this.zip=zip;
}
public void setSaloon(String chkSalon){
this.chkSalon=chkSalon ;
}
public String getSaloon(){ return this.chkSalon; }
public String getCosmo(){ return this.chkCosmo;}
public void setCosmo(String chkCosmo){
this.chkCosmo=chkCosmo ;
}
public String getStudent(){
return this.chkStudent;
}
public void setStudent(String chkStudent){
this.chkStudent=chkStudent ;
}
public String getOther(){
return this.chkOther;
}
public void setOther(String chkOther){
this.chkOther=chkOther ;
}
public String getAddInfo(){
return this.chkAddInfo;
}
public void setAddInfo(String chkAddInfo){
this.chkAddInfo=chkAddInfo ;
}
}
You are missing comma(,) after "TEXT" in your CREATE_CONTACTS_TABLE query
KEY_ZIP + " TEXT " + KEY_SALOON + " TEXT " + KEY_COSMO + " TEXT " + KEY_STUDENT
+ " TEXT " + KEY_OTHER + " TEXT " + KEY_ADD_INFO + " TEXT "
Try after doing this change. It should work, and if you still get this error, check your table structure using Android Device Monitor if you are using emulator and debug your code.
I am creating an android app (still the basic structure, without any design) from an Job site through XML feed using REST api.
Till now, I could managed to parse the XML data, displaying the List View with an POP UP menu item on each row. I am passing Data from PostBaseAdapter to MarkAsFav class. Could You please tell me if I am doing right or not? coz, I am getting no any data saved in database
Now, I have a problems:
I have 3 pop up menu item:
1. Set as Favourite
2. Share on Fb
3. email to Your friend
I am working on point number-1.
For now,I would be saving the data in SQLite Database itself. so, I am passing all the data (all the details about the job with all rows) to another activity, more over I am accepting a user given name to save the details through insertDB() in my Database.
But, unfortunately , nothing is getting saved in the database .
Can you tell me, if the data is getting passed or not and if the datas are being saved in database or not?
Please help me out. Please tell me where and how to modify the code?
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
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" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MarkAsFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Intent extras = getIntent();
if (extras != null) {
int Value = extras.getIntExtra("id",0);
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.JOBS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText((CharSequence) nam);
header.setFocusable(false);
header.setClickable(false);
}
}
}
public void run(View view) {
Intent extras = getIntent();
if (extras != null) {
int val = extras.getIntExtra("id",0);
String value1 = extras.getStringExtra("title");
String value2= extras.getStringExtra("company");
String value3= extras.getStringExtra("city");
String value4= extras.getStringExtra("state");
String value5= extras.getStringExtra("country");
String value6= extras.getStringExtra("formattedLocation");
String value7= extras.getStringExtra("source");
String value8= extras.getStringExtra("date");
String value9= extras.getStringExtra("snippet");
String value10= extras.getStringExtra("url");
String value11= extras.getStringExtra("onmousedown");
String value12= extras.getStringExtra("lattitude");
String value13= extras.getStringExtra("longitude");
String value14= extras.getStringExtra("jobkey");
String value15= extras.getStringExtra("sponsored");
String value16= extras.getStringExtra("expired");
String value17= extras.getStringExtra("formattedLocationFull");
String value18= extras.getStringExtra("formattedRelativeTime");
String headerValue = header.getText().toString();
Log.e("ERROR", "Inside run and checking Value and val");
if (val > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
PostBaseAdapter.java
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<Result> resultList;
private MainActivity mActivity;
private Context mContext;
String TAG="";
public PostBaseAdapter(Context context, ArrayList<Result> resultList) {
this.layoutInflater = LayoutInflater.from(context);
this.resultList = resultList;
this.mContext= context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Result getItem(int i) {
return resultList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int j=i;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, null);
//viewHolder = new ViewHolder(convertView);
viewHolder= new ViewHolder();
//View overFlow = convertView.findViewById(R.id.id_overflow);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.imageClick= (ImageView) convertView.findViewById(R.id.id_overflow);
convertView.setTag(viewHolder);
//overFlow.setOnClickListener(new OverflowSelectedListener(mContext, mActivity));
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Result result = resultList.get(i);
viewHolder.tvTitle.setText(result.getJobtitle());
final String jobTitle=resultList.get(i).getJobtitle();
final String company= resultList.get(i).getCompany();
final String city= resultList.get(i).getCity();
final String state= resultList.get(i).getState();
final String country= resultList.get(i).getCountry();
final String formattedLocation= resultList.get(i).getFormattedLocation();
final String source=resultList.get(i).getSource();
final String date= resultList.get(i).getDate();
final String snippet= resultList.get(i).getSnippet();
final String url= resultList.get(i).getUrl();
final String onmousedown= resultList.get(i).getOnmousedown();
final String lattitude= resultList.get(i).getLattitude();
final String longitude= resultList.get(i).getLongitude();
final String jobkey= resultList.get(i).getJobkey();
final String sponsored= resultList.get(i).getSponsored();
final String expired= resultList.get(i).getExpired();
final String formattedLocaionfull= resultList.get(i).getFormattedLocation();
final String formattedRelativeTime= resultList.get(i).getFormattedRelativeTime();
try {
viewHolder.imageClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_overflow:
final PopupMenu popup = new PopupMenu(mContext, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// Force icons to show
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id_To_Search = j + 1;
/*Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtras(dataBundle);
mContext.startActivity(intent);*/
switch (item.getItemId()) {
case R.id.email_whatsapp:
doEmailOrWhatsapp(mActivity);
return true;
case R.id.share_on_fb:
shareOnFb(mActivity);
return true;
case R.id.mark_as_fav:
//viewHolder.
//dataBundle.putString("name", result.getJobtitle());
Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtra("id",0);
intent.putExtra("title", jobTitle );
intent.putExtra("company",company );
intent.putExtra("city", city);
intent.putExtra("state",state );
intent.putExtra("country",country );
intent.putExtra("formattedLocation",formattedLocation );
intent.putExtra("source",source );
intent.putExtra("date", date);
intent.putExtra("snippet", snippet);
intent.putExtra("url", url);
intent.putExtra("onmousedown",onmousedown );
intent.putExtra("lattitude", lattitude);
intent.putExtra("longitude",longitude );
intent.putExtra("jobkey", jobkey);
intent.putExtra("sponsored",sponsored );
intent.putExtra("expired", expired);
intent.putExtra("formattedLocationFull",formattedLocaionfull );
intent.putExtra("formattedRelativeTime",formattedRelativeTime );
//intent.putExtras(dataBundle);
mContext.startActivity(intent);
return true;
default:
break;
}
return true;
}
});
//popup.show();
break;
default:
break;
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvTitle;//, tvPublishDate;
ImageView imageClick;
/* public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);*/
// imageClick=(ImageView)item.findViewById(R.id.id_overflow);
// tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
}
}
mark-fav-layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
</LinearLayout>
Result.java
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I have just updated my code and its working fine for me. I am posting it here ,so that anyone can use if needed.
MarkFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
mydb.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
if (value > 0) {
//means this is the view part not the add contact part.
/* Cursor rs = mydb.getData(value);
id_To_Update = value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText( nam);
header.setFocusable(false);
header.setClickable(false);*/
}
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
String headerValue = header.getText().toString();
String value1 = extras.getString("title");
String value2 = extras.getString("company");
String value3 = extras.getString("city");
String value4 = extras.getString("state");
String value5 = extras.getString("country");
String value6 = extras.getString("formattedLocation");
String value7 = extras.getString("source");
String value8 = extras.getString("date");
String value9 = extras.getString("snippet");
String value10= extras.getString("url");
String value11= extras.getString("onmousedown");
String value12= extras.getString("lattitude");
String value13= extras.getString("longitude");
String value14= extras.getString("jobkey");
String value15= extras.getString("sponsored");
String value16= extras.getString("expired");
String value17= extras.getString("formattedLocationFull");
String value18= extras.getString("formattedRelativeTime");
Log.e("ERROR", "Inside run and checking Value and val");
if (value > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
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" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);*/
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" Text, "+JOBS_COLUMN_NAME+" Text,"+JOBS_COLUMN_COMPANY+" Text, "+JOBS_COLUMN_CITY+" Text, "+JOBS_COLUMN_STATE+" Text, "+JOBS_COLUMN_COUNTRY+" Text,"+JOBS_COLUMN_FORMATEDLOCATION+" Text,"+JOBS_COLUMN_SOURCE+" Text,"+JOBS_COLUMN_DATE+" Text,"+JOBS_COLUMN_SNIPPET+" Text,"+JOBS_COLUMN_COMPANY+" Text,"+JOBS_COLUMN_URL+"Text,"+JOBS_COLUMN_ONMOUSEDOWN+" Text,"+JOBS_COLUMN_LATTITUDE+" Text,"+JOBS_COLUMN_LONGITUDE+"Text,"+JOBS_COLUMN_JOBKEY+" Text,"+JOBS_COLUMN_SPONSORED+" Text,"+JOBS_COLUMN_EXPIRED+" Text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" Text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" Text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
/* public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}*/
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
I have problem with sqlite database adapter in my project.I'm new to android development so I don't have much idea to how can handle this problem. I want to save user information in data base .Although no error while execution,database doesn't create? can any one help.
DatabaseAdapter :
public class DatabaseAdapter {
private final String TAG = "DatabaseAdapter";
private DatabaseOpenHelper openHelper;
public static final String TBL_PERSONS = "persons";
public static final String PERSON_ID = "_id";
public static final String PERSON_USERNAME = "_username";
public static final String PERSON_HEIGHT = "_height";
public static final String PERSON_WEIGHT = "_weight";
public static final String PERSON_AGE = "_age";
public static final String PERSON_GENDER = "_gender";
public static final String PERSON_PA = "_pa";
public static final String PERSON_BMI = "_bmivalue";
public static final String PERSON_INTERPRETATION = "_bmiInterpretation";
public static final String PERSON_IDEALWEIGHT = "_idealweight";
public static final String PERSON_DAILYCALORIES = "_dailycalories";
// ???????????
public DatabaseAdapter(Context context) {
openHelper = new DatabaseOpenHelper(context, "Persons.db", null, 1);
}
// ====================insert in
// database===========================================================
public Long insertPerson(Person person) {
SQLiteDatabase db = null;
Long id = -1L;
try {
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
db = openHelper.getWritableDatabase();
id = db.insert(TBL_PERSONS, null, values);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
if (db != null && db.isOpen())
db.close();
}
return id;
}
// ================delete from
// database=============================================================
public int deletePerson(long id) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
count = db.delete(TBL_PERSONS, PERSON_ID + "=?",
new String[] { String.valueOf(id) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===============update
// database===================================================================
public int updatePerson(Person person) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
count = db.update(TBL_PERSONS, values, PERSON_ID + "=?",
new String[] { String.valueOf(person.getId()) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===================================================================DATABASEOPENHELPER
// CLASS=========================
class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String
.format("create table %s(%$ integer primary key,%s text,%s text,%s text,%s text,%s text,%s tetx,%s text,%s text,%s text,%s text)",
TBL_PERSONS, PERSON_ID, PERSON_USERNAME,
PERSON_HEIGHT, PERSON_WEIGHT, PERSON_AGE,
PERSON_GENDER, PERSON_PA, PERSON_BMI,
PERSON_INTERPRETATION, PERSON_IDEALWEIGHT,
PERSON_DAILYCALORIES);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
person.java (I pass the user data to person.java)
package Databasedata;
public class Person {
private Long id;
private String username;
private float height;
private int weight;
private int age;
private String gender;
private String pa;
private int bmivalue;
private String bmiInterpretation;
private double idealweight;
private double dailycalories;
public double getIdealweight() {
return idealweight;
}
public void setIdealweight(double idealweight) {
this.idealweight = idealweight;
}
public double getDailycalories() {
return dailycalories;
}
public void setDailycalories(double dailycalories) {
this.dailycalories = dailycalories;
}
public int getBmivalue() {
return bmivalue;
}
public void setBmivalue(int bmivalue) {
this.bmivalue = bmivalue;
}
public String getBmiInterpretation() {
return bmiInterpretation;
}
public void setBmiInterpretation(String bmiInterpretation) {
this.bmiInterpretation = bmiInterpretation;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPa() {
return pa;
}
public void setPa(String pa) {
this.pa = pa;
}
}
MAIN ACTIVITY
public class MainActivity extends Activity {
String gender;
RadioButton maleRadioButton;
RadioButton femaleRadioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maleRadioButton = (RadioButton) findViewById(R.id.maleselected);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleselected);
final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
selectedId=genderselected.getCheckedRadioButtonId();
RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
gender= genderchoosed.getText().toString();
}
});
Button saveinformation = (Button) findViewById(R.id.saveinformation);
saveinformation.setOnClickListener(new View.OnClickListener() {
EditText weighttext = (EditText) findViewById(R.id.weighttext);
EditText heighttext = (EditText) findViewById(R.id.heighttext);
EditText usernametext = (EditText) findViewById(R.id.usernametext);
EditText agetext = (EditText) findViewById(R.id.agetext);
Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
Button saveinformation = (Button) findViewById(R.id.saveinformation);
String pa = activitytext.getSelectedItem().toString();
#Override
public void onClick(View v) {
if(maleRadioButton.isChecked()) {
gender= maleRadioButton.getText().toString();
} else {
gender = femaleRadioButton.getText().toString();
}
int weight = (int) Float.parseFloat(weighttext.getText()
.toString());
float height = Float.parseFloat(heighttext.getText()
.toString());
String username = usernametext.getText().toString();
int age = (int) Float.parseFloat(agetext.getText().toString());
String pa = activitytext.getSelectedItem().toString();
// BMI
// ============================================================================================
int Bmivalue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(Bmivalue);
float idealweight = idealweight(weight, height, gender, pa, age);
double dailycalories=dailycalories(weight,height,gender,pa,age);
// insert in to
// db==================================================================================
Person person = new Person();
person.setUsername(username);
person.setHeight(height);
person.setWeight(weight);
person.setAge(age);
person.setGender(gender);
person.setPa(pa);
person.setBmivalue(Bmivalue);
person.setBmiInterpretation(bmiInterpretation);
person.setIdealweight(idealweight);
person.setDailycalories(dailycalories);
// ?????????????????????????????????????????/
Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
MainActivity.this);
dbAdapter.insertPerson(person);
Toast.makeText(getApplicationContext(),
Bmivalue + "and you are" + bmiInterpretation,
Toast.LENGTH_LONG).show();
}
});
}
}
One Problem I see is in your insertPerson() method. Don't include the "" in the values.put()
try replacing below code
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
with
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
I am learning android development through video tutorials.
using the idea in the tutorial. I have created my own class, the database handler (Dbhandler.java) file and the (kovil.java) file. these files are working perfectly.
i want to catch the all the values from the database and display it in the list view. in my mainactivity.xml
can any one help me to do this. Thank you..
here are my codes..
Dbhandler.java file
package lk.adspace.jaffnadb;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Dbhandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jaffnatempletest";
// Temple table name
private static final String TABLE_TEMPLE = "templ";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TMPNAME = "temple_name";
private static final String KEY_TMPTYPE = "temple_type";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_IMGNAME = "image_name";
private static final String KEY_YEARBUILD = "year_build";
private static final String KEY_ADDRESS = "address";
private static final String KEY_CITY = "city";
private static final String KEY_EMAIL = "email";
private static final String KEY_WEB = "website";
private static final String KEY_TEL1 = "telephone1";
private static final String KEY_TEL2 = "telephone2";
private static final String KEY_DESCRI = "Description";
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
public Dbhandler (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TEMPLE_TABLE = "CREATE TABLE " + TABLE_TEMPLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_TMPNAME + " TEXT," + KEY_TMPTYPE + " TEXT," + KEY_LATITUDE + " TEXT," + KEY_LONGITUDE + " TEXT," + KEY_IMGNAME + " TEXT,"
+ KEY_YEARBUILD + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_CITY + " TEXT," + KEY_EMAIL + " TEXT," + KEY_WEB + " TEXT," + KEY_TEL1 + " TEXT," + KEY_TEL2 + " TEXT,"
+ KEY_DESCRI + " TEXT" + ")";
db.execSQL(CREATE_TEMPLE_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_TEMPLE);
// Create tables again
onCreate(db);
}
// Adding new temple
public void Add_Temple(kovil Kovil) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TMPNAME, Kovil.gettemplename());
values.put(KEY_TMPTYPE, Kovil.gettempletype());
values.put(KEY_LATITUDE, Kovil.getlatitude());
values.put(KEY_LONGITUDE, Kovil.getlongitude());
values.put(KEY_IMGNAME, Kovil.getimage_name());
values.put(KEY_YEARBUILD, Kovil.getyear_build());
values.put(KEY_ADDRESS, Kovil.getaddress());
values.put(KEY_CITY, Kovil.getcity());
values.put(KEY_EMAIL, Kovil.getemail());
values.put(KEY_WEB, Kovil.getwebsite());
values.put(KEY_TEL1, Kovil.gettelephone1());
values.put(KEY_TEL2, Kovil.gettelephone2());
values.put(KEY_DESCRI, Kovil.getDescription());
// Inserting Row
db.insert(TABLE_TEMPLE, null, values);
db.close(); // Closing database connection
}
// Getting single contact
kovil Get_Temple(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_TEMPLE, new String[] { KEY_ID,
KEY_TMPNAME, KEY_TMPTYPE, KEY_LATITUDE, KEY_LONGITUDE, KEY_IMGNAME, KEY_YEARBUILD, KEY_ADDRESS, KEY_CITY, KEY_EMAIL, KEY_EMAIL, KEY_WEB, KEY_TEL1, KEY_TEL2, KEY_DESCRI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
kovil Kovil = new kovil(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13));
// return contact
cursor.close();
db.close();
return Kovil;
}
// Getting All Contacts
public ArrayList<kovil> Get_Temple() {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
}
Kovil.java File
package lk.adspace.jaffnadb;
public class kovil {
//public variables
public int _id;
public String _temple_name;
public String _temple_type;
public String _latitude;
public String _longitude;
public String _image_name;
public String _year_build;
public String _address;
public String _city;
public String _email;
public String _website;
public String _telephone1;
public String _telephone2;
public String _Description;
//empty constructor
public kovil (){
}
// int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address, String city, String email, String website, String telephone1, String telephone2, String Description
public kovil(int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address,
String city, String email, String website, String telephone1, String telephone2, String Description) {
// TODO Auto-generated constructor stub
this._id= id;
this._temple_name=temple_name;
this._temple_type=temple_type;
this._latitude=latitude;
this._longitude=longitude;
this._image_name=image_name;
this._year_build=year_build;
this._address=address;
this._city=city;
this._email=email;
this._website=website;
this._telephone1=telephone1;
this._telephone2=telephone2;
this._Description=Description;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String gettemplename() {
return this._temple_name;
}
public void settemplename(String temple_name) {
this._temple_name=temple_name;
}
public String gettempletype() {
return this._temple_type;
}
public void settempletype(String temple_type) {
this._temple_type=temple_type;
}
public String getlatitude() {
return this._latitude;
}
public void setlatitude(String latitude) {
this._latitude=latitude;
}
public String getlongitude() {
return this._longitude;
}
public void setlongitude(String longitude) {
this._longitude=longitude;
}
public String getimage_name() {
return this._image_name;
}
public void setimage_name(String image_name) {
this._image_name=image_name;
}
public String getyear_build() {
return this._year_build;
}
public void setyear_build(String year_build) {
this._year_build=year_build;
}
public String getaddress() {
return this._address;
}
public void setaddress(String address) {
this._address=address;
}
public String getcity() {
return this._city;
}
public void setcity(String city) {
this._city=city;
}
public String getemail() {
return this._email;
}
public void setemail(String email) {
this._email=email;
}
public String getwebsite() {
return this._website;
}
public void setwebsite(String website) {
this._website=website;
}
public String gettelephone1() {
return this._telephone1;
}
public void settelephone1(String telephone1) {
this._telephone1=telephone1;
}
public String gettelephone2() {
return this._telephone2;
}
public void settelephone2(String telephone2) {
this._telephone2=telephone2;
}
public String getDescription() {
return this._Description;
}
public void setDescription(String Description) {
this._Description=Description;
}
}
MainActivity.java file
package lk.adspace.jaffnadb;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ArrayList<kovil> temple_data = new ArrayList<kovil>();
ListView temple_listview;
Dbhandler dbhand = new Dbhandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kovil insertData = new kovil("temple_name", "temple_type", "latitude", "longitude", "image_name", "year_build", "address",
"city", "email", "website", "telephone1", "telephone2", "Description");
Dbhandler dbhand = new Dbhandler(this);
dbhand .Add_Temple(insertData );
kovil insertData2 = new kovil("temple_name", "temple_type", "latitude", "longitude", "image_name", "year_build", "address",
"city", "email", "website", "telephone1", "telephone2", "Description");
dbhand .Add_Temple(insertData2 );
int count =dbhand .Get_Total_Temple();
TextView textView = (TextView) findViewById(R.id.count);
textView.setText(Integer.toString(count));
// i want to display all the values in a list over here.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Main Activity .xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="50dp" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/count"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/count" >
</ListView>
</RelativeLayout>
First you'll need to create a layout file that will represent how you want to display each list item.
Then you'll need to extend the BaseAdapter class so that you can decide how you want to display each Kovil class.
Once that is constructed, you can call setAdapter on your ListView.
refer these links, it might be useful to you,
1) http://www.edumobile.org/android/android-programming-tutorials/learn-how-to-create-listview-from-sqlite-database-in-android-development/
2) http://androidtuts4u.blogspot.in/2013/02/android-list-view-using-custom-adapter.html