table has no column named -Sqlite -android-my first app - java

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.

Related

Force Close when Adding and Showing data from internal database SQLite Android [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
This is my MainActivity Class
public class MainActivity extends AppCompatActivity {
TextView textView;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
DatabaseHelper db = new DatabaseHelper(this);
//inserting
db.addMessage(new Message("Halo pesan 1", "group1"));
db.addMessage(new Message("Halo pesan 2", "group1"));
db.addMessage(new Message("Halo pesan 3", "group2"));
db.addMessage(new Message("Halo pesan 4", "group2"));
//reading and displaying all message
List<Message> messageList = db.getAllMessage();
for(Message m : messageList){
String log = "ID " + m.getId() + ", Message: " + m.getMessageText() + ", Sender: " + m.getSender() + "\n";
text = text + log;
}
textView.setText(messageList.toString());
}
}
This is my Database Class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "messageManager";
private static final String TABLE_MESSAGE = "m_message";
private static final String KEY_ID = "id";
private static final String KEY_MESSAGE = "messageText";
private static final String KEY_SENDER = "sender";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_MESSAGE_TABLE = " CREATE TABLE " + TABLE_MESSAGE + "("
+KEY_ID + " INTEGER PRIMARY KEY , " + KEY_MESSAGE + "TEXT , "
+KEY_SENDER + "TEXT" + " )";
db.execSQL(CREATE_MESSAGE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i , int b){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGE);
onCreate(db);
}
void addMessage(Message message){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_MESSAGE, message.getMessageText());
values.put(KEY_SENDER, message.getSender());
db.insert(TABLE_MESSAGE,null,values);
db.close();
}
public List<Message> getAllMessage(){
List<Message> messageList = new ArrayList<>();
String selectQuery = " Select * FROM " + TABLE_MESSAGE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if (cursor.moveToFirst()){
do{
Message message = new Message();
message.setId(Integer.parseInt(cursor.getString(0)));
message.setMessageText(cursor.getString(1));
message.setSender(cursor.getString(2));
messageList.add(message);
}while (cursor.moveToNext());
}
return messageList;
}
}
and this is my model class
public class Message {
int id;
String messageText;
String sender;
public Message(){
}
public Message(String messageText , String sender){
this.messageText = messageText;
this.sender = sender;
}
public Message(int id , String messageText , String sender){
this.id = id;
this.messageText = messageText;
this.sender = sender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
}
This is the debug log
I simply just want to add some data to database and showing it to screen.
There is no error when running it, but when I debuging it there is something wrong.
I've changed the database name nor table name but still force close.
In my analysis there is something wrong with creating a database but I don't know how to solve it.
replace oncreate CREATE_MESSAGE_TABLE string
String CREATE_MESSAGE_TABLE = "CREATE TABLE " + TABLE_MESSAGE + "("
+KEY_ID + " INTEGER PRIMARY KEY," + KEY_MESSAGE + " TEXT,"
+KEY_SENDER + " TEXT" + ")";

Why dose update creates new id in database?

I am trying to update the record, whenever I am updating a record new id is generated with the updated values. The update should happen to the same id. What can be the reason?
Create table :
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT,"
+ KEY_LOCATION + " TEXT,"
+ KEY_NOTIFICATION_TIME + " DATE" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
update function :
public int updateEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE,event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
// updating row
return db.update(TABLE, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.getId()) });
}
Calling update function :
db = new EventTableHelper(getApplicationContext());
eventData = new EventData();
db.updateEvent(eventData);
Thank you.
EDIT :
My constructor in EventData is this:
public EventData(String title,String fromDate,String toDate,String dayOfWeek,String location,String notificationTime){
this.title = title;
this.fromDate = fromDate;
this.toDate = toDate;
this.dayOfWeek = dayOfWeek;
this.location = location;
this.notificationTime = notificationTime;
}
and I am adding and updating value using eventData object:
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location,notificationTime));
db.updateEvent(eventData);
The id is getting increased, I am not passing any value to id.
EventData class
public class EventData {
public int id;
public String title;
public String fromDate;
public String toDate;
public String location;
public String dayOfWeek;
public String notificationTime;
public EventData(){}
public EventData(String title,String fromDate,String toDate, String location){
this.title = title;
this.fromDate = fromDate;
this.toDate = toDate;
this.location = location;
}
public EventData(int id,String title,String fromDate,String toDate,String dayOfWeek,String location,String notificationTime){
this.title = title;
this.fromDate = fromDate;
this.toDate = toDate;
this.dayOfWeek = dayOfWeek;
this.location = location;
this.notificationTime = notificationTime;
}
/* public EventData(String title,String fromDate,String toDate,String dayOfWeek,String location,String notificationTime){
this.id = id;
this.title = title;
this.fromDate = fromDate;
this.toDate = toDate;
this.dayOfWeek = dayOfWeek;
this.location = location;
this.notificationTime = notificationTime;
}*/
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public void setLocation(String location) {
this.location = location;
}
public void setDayOfWeek(String dayofWeek) {
this.dayOfWeek = dayofWeek;
}
public void setNotificationTime(String notificationTime) {
this.notificationTime = notificationTime;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getFromDate() {
return fromDate;
}
public String getToDate() {
return toDate;
}
public String getLocation() {
return location;
}
public String getDayOfWeek() {
return dayOfWeek;
}
public String getNotificationTime() {
return notificationTime;
}
}
I am creating events with child view so I want to update the event on which i will click. For that i have used setTag method to pass id of view.
This is my day fragment
dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);
int id = i.getIntExtra("id",0);
mDb = new EventTableHelper(getActivity());
events = mDb.getAllEvents("Mon");
int tag = 0;
for (EventData eventData : events) {
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String dateTo = eventData.getToDate();
String title = eventData.getTitle();
String location = eventData.getLocation();
if (dateTo != null) {
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, tag);
tag++;
}
return view;
}
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,int tag) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
if(location.equals(""))
{
tvTitle.setText("Event : " + title);
}
else
{
tvTitle.setText("Event : " + title + " (At : " + location +")");
}
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setTag(tag);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
editMode = true;
i.putExtra("EditMode",editMode);
int tag = 0;
tag =(int)v.getTag();
i.putExtra("tag",tag);
startActivityForResult(i,1);
}
});
}
As we discussed in comments. I think you don't need to be so complex as you are being now,
Just simply do like this,
db.update(TABLE, values, KEY_ID = id, null);
where id means the Integer value OR the value of column KEY_ID that you want to update. Like the value of id will be 5 if you want to update the row with id of 5.

User Login with SQLite database java.lang.NullPointerException

I'm having a problem using my database to check the username and password of the user. I'm using a query to select the specific row and then check the password against what was entered by the user. The error I am getting is a java.lang.NullPointerException in my login page when i call the
Users userlogin = db.userlogin(usernameinput);
After looking at the method I'm thinking its the first cursor that causes it to fail
cursor.getInt(0);
What I'm wondering is am I right in thinking this and what can I do to change it?
I've tried changing the if statement to
If(cursor.getcount() > 0)
and still no luck.
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
loginbutton = (Button) findViewById(R.id.loginbtn);
usernameuser = (EditText) findViewById(R.id.usernameInsert);
passworduser = (EditText) findViewById(R.id.passwordInsert);
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
Database handler Query used to check login:
public Users userLogin(String username) {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor != null)
cursor.moveToFirst();
Users users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
cursor.close();
return users;
}
04-08 13:05:33.194 2565-2565/com.example.john.fitnessapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.john.fitnessapp, PID: 2565
java.lang.NullPointerException
at com.example.john.fitnessapp.LoginPage$1.onClick(LoginPage.java:42)
at android.view.View.performClick(View.java:4569)
at android.view.View$PerformClick.run(View.java:18553)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
at dalvik.system.NativeStart.main(Native Method)
user class:
public class Users {
int _id, _age;
String _username, _password, _email, _gender;
double _startWeight, _currentWeight, _weightChange, _height, _BMI, _BMR, _reqCal, _monCal, _tuesCal, _wedCal, _thurCal, _friCal, _satCal, _sunCal;
public Users(){}
public Users(int _id, String _username, String _password, int _age, String _email, String _gender, double _height, double _startWeight,
double _currentWeight, double _weightChange, double _BMI, double _BMR, double _reqCal, double _monCal, double _tuesCal, double _wedCal,
double _thurCal, double _friCal, double _satCal, double _sunCal){
this._id = _id;
this._username = _username;
this._password = _password;
this._age = _age;
this._email = _email;
this._gender = _gender;
this._height = _height;
this._startWeight = _startWeight;
this._currentWeight = _currentWeight;
this._weightChange = _weightChange;
this._BMI = _BMI;
this._BMR = _BMR;
this._reqCal = _reqCal;
this._monCal = _monCal;
this._tuesCal = _tuesCal;
this._wedCal = _wedCal;
this._thurCal = _thurCal;
this._friCal = _friCal;
this._satCal = _satCal;
this._sunCal = _sunCal;
}
public int get_id(){
return this._id;
}
public void set_id(int id){
this._id = id;
}
public String get_username(){
return this._username;
}
public void set_username(String username){
this._username = username;
}
public String get_password(){
return this._password;
}
public void set_password(String password){
this._password = password;
}
public int get_age(){
return this._age;
}
public void set_age(int age){
this._age = age;
}
public String get_email(){
return this._email;
}
public void set_email(String email){
this._email = email;
}
public String get_gender(){
return this._gender;
}
public void set_gender(String gender){
this._gender = gender;
}
public double get_height(){
return this._height;
}
public void set_height(double height){
this._height = height;
}
public double get_startWeight(){
return this._startWeight;
}
public void set_startWeight(double startWeight){
this._startWeight = startWeight;
}
public double get_currentWeight(){
return this._currentWeight;
}
public void set_currentWeight(double currentWeight){
this._currentWeight = currentWeight;
}
public double get_weightChange(){
return this._weightChange;
}
public void set_weightChange(){
this._weightChange = _currentWeight - _startWeight;
}
public double get_BMI(){
return this._BMI;
}
public void set_BMI(double BMI){
this._BMI = BMI;
}
public double get_BMR(){
return this._BMR;
}
public void set_BMR(double BMR){
this._BMR = BMR;
}
public double get_reqCal(){
return this._reqCal;
}
public void set_reqCal(double reqCal){
this._reqCal = reqCal;
}
public double get_monCal(){
return this._monCal;
}
public void set_monCal(double monCal){
this._monCal = monCal;
}
public double get_tuesCal(){
return this._tuesCal;
}
public void set_tuesCal(double tuesCal){
this._tuesCal = tuesCal;
}
public double get_wedCal(){
return this._wedCal;
}
public void set_wedCal(double wedCal){
this._wedCal = wedCal;
}
public double get_thurCal(){
return this._thurCal;
}
public void set_thurCal(double thurCal){
this._thurCal = thurCal;
}
public double get_friCal(){
return this._friCal;
}
public void set_friCal(double friCal){
this._friCal = friCal;
}
public double get_satCal(){
return this._satCal;
}
public void set_satCal(double satCal){
this._satCal = satCal;
}
public double get_sunCal(){
return this._sunCal;
}
public void set_sunCal(double sunCal){
this._sunCal = sunCal;
}
}
Databasehandler:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String TAG = "DBHelper";
//DATABASE VERSION
private static int DATABASE_VERSION = 1;
//DATABASE NAME
private static final String DATABASE_NAME = "AppDatabase";
//TABLE NAMES
private static final String TABLE_USERS = "Users_Table";
private static final String TABLE_PRODUCTS = "Products_Table";
//COMMON COLUMN NAMES
private static final String KEY_USER_ID = "User_ID";
private static final String KEY_PRODUCT_ID = "Product_ID";
//USER TABLE
private static final String KEY_USERNAME = "Username";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_AGE = "Age";
private static final String KEY_EMAIL = "Email";
private static final String KEY_GENDER = "Gender";
private static final String KEY_HEIGHT = "Height";
private static final String KEY_CURRENT_WEIGHT = "Current_Weight";
private static final String KEY_START_WEIGHT = "Start_Weight";
private static final String KEY_WEIGHT_CHANGE = "Weight_Change";
private static final String KEY_BMI = "BMI";
private static final String KEY_BMR = "BMR";
private static final String KEY_REQ_CAL = "Required_Calories";
private static final String KEY_MON_CAL = "Monday_Calories";
private static final String KEY_TUES_CAL = "Tuesday_Calories";
private static final String KEY_WED_CAL = "Wednesday_Calories";
private static final String KEY_THUR_CAL = "Thursday_Calories";
private static final String KEY_FRI_CAL = "Friday_Calories";
private static final String KEY_SAT_CAL = "Saturday_Calories";
private static final String KEY_SUN_CAL = "Sunday_Calories";
//PRODUCT TABLE
private static final String KEY_ITEMNAME = "Item_name";
private static final String KEY_ITEMCALORIES = "Item_Calories";
//
private static final String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "( "
+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_AGE + " INTEGER, "
+ KEY_EMAIL + " TEXT, "
+ KEY_GENDER + " TEXT, "
+ KEY_HEIGHT + " DOUBLE, "
+ KEY_START_WEIGHT + " DOUBLE, "
+ KEY_CURRENT_WEIGHT + " DOUBLE, "
+ KEY_WEIGHT_CHANGE + " DOUBLE, "
+ KEY_BMI + " DOUBLE, "
+ KEY_BMR + " DOUBLE, "
+ KEY_REQ_CAL + " DOUBLE, "
+ KEY_MON_CAL + " DOUBLE, "
+ KEY_TUES_CAL + " DOUBLE, "
+ KEY_WED_CAL + " DOUBLE, "
+ KEY_THUR_CAL + " DOUBLE, "
+ KEY_FRI_CAL + " DOUBLE, "
+ KEY_SAT_CAL + " DOUBLE, "
+ KEY_SUN_CAL + " DOUBLE ); ";
private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "( " + KEY_PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_ITEMNAME + " TEXT, "
+ KEY_ITEMCALORIES + " DOUBLE );";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,
"Upgrading the database from version " + oldVersion + " to " + newVersion);
DATABASE_VERSION = 2;
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
Edit: Make sure you initialize your class that extends SQLiteOpenHelper.
Make sure you call:
db = new DatabaseHandler(this);
If you don't initialize db then it will be null when you call db.userLogin(usernameinput);, and that might be the cause of the NullPointerException that you're getting.
You could just call it in `onCreate()' like this:
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
db = new DatabaseHandler(this); //initialize the DatabaseHandler
//........
In addition, it looks like you're only querying three columns of the database, and trying to access twenty columns in the cursor.
Also, you should check the return value of cursor.moveToFirst().
In general, the cursor will never be null.
This will probably make it work short term, but you might want to consider re-factoring your code such that you don't have to query all rows to make it work:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
//String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, null, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
}
cursor.close();
return users;
}
Ideally you would create another constructor for your Users class that could just take the three parameters that you need in this case.
Your modified code would be something like this:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2))
}
cursor.close();
return users;
}
Also, it would be good to check for null return value from your userLogin() function:
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (userlogin != null && usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});

Android saving data from edit texts fields to database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to SQLite. I have an activity in which I have different fields like Name,Email,Date of Birth etc. When user fill the information and clicks the save button I want it to get saved to the database. But I am stuck in mid way and don't know what to do.How to save the data from Edit Text Views to the database on Save Button click.Please help me.
I am sharing my code.
DataBaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NewUserDb.db";
private static final String TABLE_INFO = "info";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_GOAL = "userGOAL";
public static final String COLUMN_NAME = "userName";
public static final String COLUMN_EMAIL = "userEmail";
public static final String COLUMN_DOB = "userDOB";
public static final String COLUMN_HEIGHT = "userHeight";
public static final String COLUMN_WEIGHT = "userWeight";
public static final String COLUMN_GENGER = "userGender";;
public static final String COLUMN_ZIP = "userZIP";
private static final String[] COLUMNS = { COLUMN_ID, COLUMN_GOAL,
COLUMN_NAME, COLUMN_EMAIL, COLUMN_DOB, COLUMN_HEIGHT,
COLUMN_WEIGHT, COLUMN_GENGER, COLUMN_ZIP };
// http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
/*
* public DatabaseHelper(Context context, String name, CursorFactory
* factory, int version) { super(context, name, factory, version); // TODO
* Auto-generated constructor stub
*
* }
*/
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE User ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "gaol TEXT, "
+ "name TEXT )";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS users");
// create fresh books table
this.onCreate(db);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void addUser(NewUserDb newuserdb) {
// for logging
// Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(COLUMN_GOAL, newuserdb.getGoal()); // get title
values.put(COLUMN_NAME, newuserdb.getName()); // get author
values.put(COLUMN_EMAIL, newuserdb.getEmail());
values.put(COLUMN_DOB, newuserdb.getDob());
values.put(COLUMN_HEIGHT, newuserdb.getHeight());
values.put(COLUMN_WEIGHT, newuserdb.getWeight());
values.put(COLUMN_GENGER, newuserdb.getGender());
values.put(COLUMN_ZIP, newuserdb.getZip());
// 3. insert
db.insert(TABLE_INFO, // table
null, // nullColumnHack
values); // key/value -> keys = column names/ values = column
// values
// 4. close
db.close();
}
public NewUserDb getNewUserDb(int id) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor = db.query(TABLE_INFO, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
NewUserDb newUserdb = new NewUserDb();
newUserdb.setId(Integer.parseInt(cursor.getString(0)));
newUserdb.setGoal(cursor.getString(1));
newUserdb.setName(cursor.getString(2));
newUserdb.setEmail(cursor.getString(3));
newUserdb.setDob(cursor.getString(4));
newUserdb.setHeight(cursor.getString(5));
newUserdb.setWeight(cursor.getString(6));
newUserdb.setGender(cursor.getString(7));
newUserdb.setZip(cursor.getString(8));
// Log.d("getBook("+id+")", book.toString());
// 5. return book
return newUserdb;
}
// Deleting single book
public void deleteUser(NewUserDb newuserDB) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_INFO, COLUMN_ID + " = ?",
new String[] { String.valueOf(newuserDB.getId()) });
// 3. close
db.close();
Log.d("deleteBook", newuserDB.toString());
}
}
NewUserDb.java
public class NewUserDb {
private int id;
private String goal;
private String name;
private String email;
private String dob;
private String height;
private String weight;
private String gender;
private String zip;
public NewUserDb() {
}
public NewUserDb(int id, String goal, String name, String email,
String dob, String height, String weight, String gender, String zip) {
super();
this.id = id;
this.goal = goal;
this.name = name;
this.email = email;
this.dob = dob;
this.height = height;
this.weight = weight;
this.gender = gender;
this.zip = zip;
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "User [id=" + id + ", goal=" + goal + ", name=" + name
+ ", email=" + email + ", dob=" + dob + ", height=" + height
+ ", weight=" + weight + ", gender=" + gender + ", zip =" + zip
+ "]";
}
}
AccountActivity.java
public class AccountActivity extends Activity {
private EditText et_weight, et_height, et_email, et_dob, et_name;
private Button btn_uploadPhoto, btn_shootPhoto, btn_del, btn_save;
private Switch genderSwitch;
private DatePickerDialog datePickerDialog;
private String year;
private String month;
private String day;
DatabaseHelper dbh = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accounts);
btn_shootPhoto = (Button) findViewById(R.id.button1);
btn_uploadPhoto = (Button) findViewById(R.id.button2);
btn_del = (Button) findViewById(R.id.btn_del);
btn_save = (Button) findViewById(R.id.btn_save);
et_dob = (EditText) findViewById(R.id.et_dob);
genderSwitch = (Switch) findViewById(R.id.mySwitch);
et_name = (EditText) findViewById(R.id.et_name);
et_email = (EditText) findViewById(R.id.et_email);
et_height = (EditText) findViewById(R.id.et_height);
et_height.setInputType(InputType.TYPE_CLASS_NUMBER);
et_weight = (EditText) findViewById(R.id.et_weight);
et_weight.setInputType(InputType.TYPE_CLASS_NUMBER);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//what to do here ??
}
});
}
try .getText() on your EditText
like yourEditText.getText(); and set it into your NewUserDb and pass the NewUserDb object into addUser method of your DatabaseHelper class
First you declare database create table query string in your DatabaseHelper class like this:
private static final String DATABASE_CREATE_USER = "create table UserInfo("
+ "_id VARCHAR(20)," + "userGOAL VARCHAR(20),"
+ "userName VARCHAR(20)," + "userEmail VARCHAR(20),"
+ "userDOB VARCHAR(20)," + "userHeight VARCHAR(10),"
+ "userWeight VARCHAR(10)," + "userGender VARCHAR(10),"
+ "userZIP VARCHAR(10) "+ ")";
Then write inside onCreate method of DatabaseHelper
db.execSQL(DATABASE_CREATE_USER);
Then declare object of SqliteDatabase and DatabseHelper in your AcountActivity like this:
DatabaseHelper dbHelper;
SQLiteDatabase db;
Afer this write following code inside your button onClick method:
dbHelper= new DatabaseHelper(ActountActivity.this);
db = dbHelper.getWritableDatabase();
ContentValues insertValues = new ContentValues();
insertValues.put("_id", "User_Id");
insertValues.put("userGOAL", "User_Goal");
insertValues.put("userName", "User_Name");
insertValues.put("userEmail", "User_Email");
insertValues.put("userDOB", "User_DOB");
insertValues.put("userHeight", "User_Height");
insertValues.put("userWeight", "User_Weight");
insertValues.put("userGender", "User_Gender");
insertValues.put("userZIP", "User_Zip");
db.insert("UserInfo", null, insertValues);
db.close();
May this help you.

Displaying the values from sqllite database to listview in my main activity. Android

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

Categories