Building Database and outputting data in Android - java

I've built a database class in Android using SQLite, so far it just creates a database and inputs data, however the only log report I see is that the data has been input, but the log never shows for the database creation.
I have also seen people have a .db file in their assets folder, mine is not created.
so:
1) How come it's not showing the log error for building the database, and also is there meant to be a .db file created through SQLite? It's my first time using it.
2) If it is creating, how can I call the List from the getData() method and output it in MainActivity? I've tried using intents but once I realised I wasn't getting the log report from the database creation so I need that sorted before anything.
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("T", "T", 5, "T", "T", "T");
List<tableStudents> outputList = db.getData();
}
DB.java
package com.example.project;
import java.util.ArrayList;
import java.util.List;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + "TEXT");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
//Log for admin insert
Log.d("DB", "Inserted Successfully");
return true;
}
}

#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Matt Murphy please go through this link for each detail for your project
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/.

Related

How to get database value into edit text in android

Here is my code
Databasehandler.java
package com.example.mybucky.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.prefs.Preferences;
/**
* Created by Satyajeet Sen on 20/12/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Register.db" ;
private static final int DATABASE_VERSION = 1 ;
private static final String TABLE_REGISTER = "REGISTER";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
private static final String COL_AGE = "age";
SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "("
+ COL_ID + " INTEGER PRIMARY KEY ," + COL_NAME + " TEXT ,"
+ COL_USERNAME + " TEXT ," + COL_PASSWORD + " TEXT ," + COL_AGE + " INTEGER "+")";
db.execSQL(CREATE_REGISTER_TABLE);
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
this.onCreate(db);
}
public void insertDetails(LoginRegisterBean l){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query ="SELECT * FROM "+TABLE_REGISTER;
Cursor cursor =db.rawQuery(query,null);
int count=cursor.getCount();
values.put(COL_ID,count);
// Contact Name
values.put(COL_NAME, l.getName());
values.put(COL_USERNAME, l.getUsername());
values.put(COL_PASSWORD, l.getPassword());
values.put(COL_AGE, l.getAge());
db.insert(TABLE_REGISTER,null,values);
db.close();
}
public String searchPass(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public String searchUser(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
a="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return a;
}
LoginRegisterBean getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_REGISTER, new String[] { COL_ID,
COL_USERNAME,COL_AGE }, COL_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LoginRegisterBean retrievecontact = new LoginRegisterBean(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)));
// return contact
return retrievecontact;
}
}
UserAreaActivity.java 2edit texts one for age and other for username. Aim:-to display values of age nd username from database to edittext
package com.example.mybucky.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.example.mybucky.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class UserAreaActivity extends AppCompatActivity {
DatabaseHandler helper = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final EditText etUsername = (EditText) findViewById(R.id.username);
final EditText etAge = (EditText) findViewById(R.id.age);
final TextView tvwelcome = (TextView) findViewById(R.id.tvwelcome);
public void retrievefromdb(LoginRegisterBean l){
List<LoginRegisterBean> lst =new ArrayList<LoginRegisterBean>();
for(int i=0;i<3;i++){
lst.add( helper.getContact(i));
}
}
}
}
I have a method returning a single contact in Databasehandler class but i dont need password to be displayed. Display fields only age and username in activity UserAreaActivity.
Welcome user!Your age is
age
---edit field------
username
---edit field-----

How to pass list-view data to SQLite database?

I'm building message app and my message and number are showing in list-view but I'm not sure how to pass the list-view data to SQLite database? This is my list view code looks like but not sure how to pass the data to database.
package com.example.sunny.messager;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ListView lv=(ListView)findViewById(R.id.SmsList);
if(fetchInbox()!=null){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fetchInbox());
lv.setAdapter(adapter);
}
}
public ArrayList<String> fetchInbox(){
ArrayList<String> sms=new ArrayList<String>();
Uri uriSms=Uri.parse("content://sms/");
Cursor cursor=getContentResolver().query(uriSms, new String[]{"_id","address","date","body"}, null, null, null);
cursor.moveToFirst();
while(cursor.moveToNext()){
String address=cursor.getString(1);
String body=cursor.getString(3);
sms.add("Number: " +address+"\n Message: " +body);
}
return sms;
}
}
You need to use these classes SQLiteDatabase and and SQLiteOpenHelper.
SQLiteDatabase is the class for us to perform CRUD function.
SQLiteOpenHelper is a helper class to manage database creation and version management.
Now let’s start code on table structure portion first – create table in Android. We will create a file name SMSData.java , and the code in this file will look like this
package com.example.sqlitedb;
public class SMSData {
// Labels table name
public static final String TABLE = "SMSData";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_number = "number";
public static final String KEY_message= "message";
// property help us to keep data
public int SMSData_ID;
public int number;
public String message;
}
We’ll create a class and name it DBHelper.java and code in this file will look like this, to ease on understand code line by line i put comment in code.
package com.example.sqlitedb;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "crud.db";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//All necessary tables you like to create will create here
String CREATE_TABLE_SMSDATA= "CREATE TABLE " + SMSData.TABLE + "("
+ SMSData.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ SMSData.KEY_number+ " INTEGER, "
+ SMSData.KEY_message+ " TEXT )";
db.execSQL(CREATE_TABLE_SMSDATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
db.execSQL("DROP TABLE IF EXISTS " + SMSData.TABLE);
// Create tables again
onCreate(db);
}
}
With above 2 steps, SMSData table will be created when app get started and now we could code the CRUD functions! Create SMSDataRepo.java, the purpose of this class is to perform CRUD on the SMSData table. The code in this file will look like this.
package com.example.sqlitedb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashMap;
public class SMSDataRepo {
private DBHelper dbHelper;
public SMSDataRepo(Context context) {
dbHelper = new DBHelper(context);
}
public int insert(SMSData sMSData) {
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// Inserting Row
long SMSData_Id = db.insert(SMSData.TABLE, null, values);
db.close(); // Closing database connection
return (int) SMSData_Id;
}
public void delete(int SMSData_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// It's a good practice to use parameter ?, instead of concatenate string
db.delete(SMSData.TABLE, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData_Id) });
db.close(); // Closing database connection
}
public void update(SMSData sMSData) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// It's a good practice to use parameter ?, instead of concatenate string
db.update(SMSData.TABLE, values, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData.SMSData_ID) });
db.close(); // Closing database connection
}
public ArrayList<HashMap<String, String>> getSMSDataList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number+
SMSData.KEY_message+ "," +
" FROM " + SMSData.TABLE;
//SMSData sMSData= new SMSData();
ArrayList<HashMap<String, String>> sMSDataList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> sMSData= new HashMap<String, String>();
sMSData.put("number", cursor.getString(cursor.getColumnIndex(SMSData.KEY_number)));
sMSData.put("message", cursor.getString(cursor.getColumnIndex(SMSData.KEY_message)));
sMSDataList.add(sMSData);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSDataList;
}
public SMSData getSMSDataById(int Id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number + "," +
SMSData.KEY_message +
" FROM " + SMSData.TABLE
+ " WHERE " +
SMSData.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount =0;
SMSData sMSData= new SMSData();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );
if (cursor.moveToFirst()) {
do {
sMSData.SMSData_ID =cursor.getInt(cursor.getColumnIndex(SMSData.KEY_ID));
sMSData.number=cursor.getInt(cursor.getColumnIndex(SMSData.KEY_number));
sMSData.message=cursor.getString(cursor.getColumnIndex(SMSData.KEY_message));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSData;
}
}

Android SQLite problems, how to display data

Hi guys I'm currently creating an Android Application on Eclipse through various online tutorials. I have got as far as creating a SQLite database and being able to manually input information - although I'm not quite sure how to delete the information yet. What I would like is for the user to click a button and then it will display the information that they have inputted on a profile page - at the moment it is only two fields. I have spent hours going through various tutorials and research and just can not seem to get it to work. If anybody has the time to have a look through my code and tell me how I should call the methods to add new data via a button then it would be greatly appreciated. I think I am loosing my mind. I also understand I may not have gone around the correct way of setting things up but I am still learning.
Here is my DatabaseHandler.java file
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
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," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " 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);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_EMAIL, contact.getEmail()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setEmail(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And below is my page that so far just sends forced information to the database as you will see.
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Addrecord extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Dan", "dljbrown#icloud.com"));
db.addContact(new Contact("Pash", "pashj#hotmail.com"));
db.addContact(new Contact("Nigel", "Dancinboyforever#hotmail.com"));
db.addContact(new Contact("Jit", "Jit#hotmail.com"));
// Log.d("Delete: ", "Deleting..");
// db.deleteContact(new Contact("Dan", "dljbrown#icloud.com"));
// db.deleteContact(new Contact("Pash", "pashj#hotmail.com"));
// db.deleteContact(new Contact("Nigel",
// "Dancinboyforever#hotmail.com"));
// db.deleteContact(new Contact("Jit", "dljbrown#icloud.com"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
+ " ,Email: " + cn.getEmail();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
So instead of the information being passed straight to the database and displayed in the log like below I would like the user to of pressed a button from a previous page and I will display their information.
Thanks if anybody gets round to replying!!
Here is the activity that I currently link to the "Addrecord" activity, once "Page1" in the list view has been clicked then I would like it to display the users information (Sample info at the moment)
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Home extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
populateListView();
registerClickCallback();
}
public void populateListView() {
String[] homelist = { "Page1", "Page2", "Page3", "Page4", "Page5" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_home, homelist);
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setAdapter(adapter);
}
public void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// NOW COPY AND PASTE FOR ALL THE OTHERS
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
Intent myintent = new Intent(getApplicationContext(),
Addrecord.class);
startActivity(myintent);
}
if (position == 1) {
Intent myintent2 = new Intent(getApplicationContext(),
Pagetwo.class);
startActivity(myintent2);
}
if (position == 2) {
Intent myintent3 = new Intent(getApplicationContext(),
Pagethree.class);
startActivity(myintent3);
}
if (position == 3) {
Intent myintent4 = new Intent(getApplicationContext(),
Pagefour.class);
startActivity(myintent4);
}
if (position == 4) {
Intent myintent5 = new Intent(getApplicationContext(),
Pagefive.class);
startActivity(myintent5);
}
if (position == 5) {
Intent myintent6 = new Intent(getApplicationContext(),
Pagesix.class);
startActivity(myintent6);
}
}
});
}

SQLite database ..onCreate() is not being called

Kohli.java
package com.kohli;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
public class KohlifActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("KOHLIActivity", "qwert11111111");
setContentView(R.layout.main);
Log.i("KOHILActivity", "qwert22222222222");
DbHelper1 DbHelper=new DbHelper1(this) ;
Log.i("KOHLIfActivity", "qwert3333333333");
}
}
DbHelper1.java
package com.kohli;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DbHelper1 extends SQLiteOpenHelper
{
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
Log.d(TAG, "constructor111111");
//System.out.println("dbhelper constructor");
}
// Called only once, first time the DB is created
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + " (" + C_ID + " int primary key, "
+ C_CREATED_AT + " int, " + C_USER + " text, " + C_TEXT + " text)";
db.execSQL(sql);
Log.d(TAG, "onCreated sql:22222222 ");
//System.out.println("dbhelper oncreate");
}
// Called whenever newVersion != oldVersion
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Typically do ALTER TABLE statements, but...we're just in development,
// so:
db.execSQL("drop table if exists " + TABLE); // drops the old database
Log.d(TAG, "onUpdated 33333333");
//System.out.println("dbhelper onupgrade");
onCreate(db); // run onCreate to get new database
}
}
i wrote the following code to make a database with a table... the output at logcat is :: qwert111111 qwert22222 constructor111111 qwert3333 .. that is the oncreate function is not being called so the database is also not created...
The database isn't actually created until you call getWritableDatabase() on the
dbHelper object.

Android Development - Null Pointer Exception on Database Insert

OK, well I've been working on a simple app that allows users to save notes to contacts. It lists the contacts from the phone. User clicks on a contact and the notes entries that are related to the contact based on the contact ID are shown. The user can then add a new note by Menu>Add note. I can get all the way through the app but it wont save the data entered in the form to the database. When I try to save, I get a Null Pointer Exception. Nothing crashes, it just returns to the previous activity and doesn't do anything. I am kind of new to programming and have been teaching myself android for the past week and a half, so it could be something really simple. I have been digging around the web and frequently come to Stack Overflow to check for answers but cant seem to find anything on this one. Also, I'm not sure what code is needed so I'm just going to post the code for my form activity and my dbadapter. Thanks in advance for any help!
This is the activity used to enter the data:
package com.onyx.formapp23;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.onyx.formapp23.MyDbAdapter;
public class FormsNewNote extends Activity {
String mIntentString;
int contactId;
EditText contactIdEdit, titleEdit, bodyEdit;
long dateTimeValue;
Button submitBtn, discardBtn;
private MyDbAdapter db = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forms_newnote);
Bundle extras = getIntent().getExtras();
mIntentString = extras.getString("contactId");
db = new MyDbAdapter(this);
contactIdEdit = (EditText) findViewById(R.id.noteFormContactId);
contactIdEdit.setText(mIntentString);
contactId = Integer.parseInt(mIntentString);
titleEdit = (EditText) findViewById(R.id.noteFormTitle);
bodyEdit = (EditText) findViewById(R.id.noteFormBody);
dateTimeValue = java.lang.System.currentTimeMillis();
submitBtn = (Button) findViewById(R.id.noteFormSave);
discardBtn = (Button) findViewById(R.id.noteFormDiscard);
submitBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try{
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
db.createNote(contactId, titleInsert, bodyInsert, dateTimeValue);
} catch (Exception e) {
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
e.printStackTrace();
Context context = getApplicationContext();
CharSequence text = "SQL Exception Thrown: " + e + "\nTitle: " + titleInsert + "\nBody: " + bodyInsert;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
finish();
}
});
}
}
This is my Db adapter class:
package com.onyx.formapp23;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDbAdapter {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_CONTACTID = "contactId";
public static final String KEY_ROWID = "_id";
public static final String KEY_DATETIME = "datetime";
private static final String TAG = "MyDbAdapter";
private static final String DATABASE_CREATE =
"create table contactNotes (_id integer primary key autoincrement, contactId integer, title text not null, body text not null, datetime long);";
private static final String DATABASE_NAME = "OnyxDatabase";
private static final String DATABASE_TABLE = "contactNotes";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public MyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public MyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(int contactId, String title, String body, long datetime) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CONTACTID, contactId);
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_DATETIME, datetime);
return mDb.insertOrThrow(DATABASE_TABLE, null, initialValues);
}
public void createNote2(int contactId, String title, String body) {
mDb.execSQL("insert into " + DATABASE_TABLE + " (" + KEY_CONTACTID + ", " + KEY_TITLE + ", " + KEY_BODY + ", " + KEY_DATETIME + ") values(" + contactId + ", " +
title + ", " + body + ", " + java.lang.System.currentTimeMillis() + ");");
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_CONTACTID,
KEY_BODY, KEY_DATETIME}, null, null, null, null, null);
}
public Cursor fetchNotesForContact(String contactId) {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CONTACTID, KEY_TITLE, KEY_BODY, KEY_DATETIME}, KEY_CONTACTID + " = " + contactId, null, null, null, new String (KEY_DATETIME +
" COLLATE LOCALIZED ASC"));
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String title, String body) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
And here is the Trace from the Eclipse Debug:
Thread [<1> main] (Suspended (entry into method createNote in MyDbAdapter))
MyDbAdapter.createNote(int, String, String, long) line: 58
FormsNewNote$1.onClick(View) line: 43
Button(View).performClick() line: 2447
View$PerformClick.run() line: 9025
ViewRoot(Handler).handleCallback(Message) line: 587
ViewRoot(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4628
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 870
ZygoteInit.main(String[]) line: 628
NativeStart.main(String[]) line: not available [native method]
Doesn't look like you are calling MyDbAdapter.open() anywhere so in createNote() mDb is null.

Categories

Resources