Regarding Android Database - java

Hot To Create A Table in database only once and insert data into that table multiple times in android using SQLite DB...??

You should be sub-classing SQLiteOpenHelper and making use of its convenience methods which will remove a lot of the complexity of using SQLite. See Data Storage
Take a look at the NotePadProvider sample.

This is my activity class
public class d extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String name=getIntent().getStringExtra("name");
String email=getIntent().getStringExtra("email");
String phone=getIntent().getStringExtra("phone");
Log.e("d3","came to other activity");
SmartDBHelper d=new SmartDBHelper(getApplicationContext());
d.open();
d.insertTitle(name, phone, email);
Cursor c=d.getAllTitles();
// c.getColumnName(0);
for( int i=0;i<c.getCount();i++){
if(c.moveToNext()){
Log.e("c", ""+ c.getString(0) );
Log.e("d", ""+ c.getString(1) );
Log.e("d4", ""+ c.getString(2) );
}
Log.e("r",""+c.getCount());
finish();
}
}
}
here is my sqllite class
public class SmartDBHelper extends SQLiteOpenHelper {
private SQLiteDatabase dBH;
private static final String DATABASE_NAME = "yo.db";
private static final int DATABASE_VERSION = 2;
private static final String NOTIFY_TABLE_NAME = "user_notify_data";
private static final String HR_TABLE_NAME = "user_hr_data";
private static final String NOTIFY_TABLE_CREATE =
"CREATE TABLE " + NOTIFY_TABLE_NAME + " (counter INTEGER PRIMARY KEY, " +
"userresponse TEXT, " +
"notifytime TEXT);";
private static final String HR_TABLE_CREATE =
"CREATE TABLE " + HR_TABLE_NAME +
" (counter INTEGER PRIMARY KEY, " +
"hr TEXT, " +
"act TEXT, " +
"timestamp TEXT);";
public SmartDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.e("smartdbhelper", "before creation");
db.execSQL(NOTIFY_TABLE_CREATE);
Log.e("smartdbhelper", "middle creation");
db.execSQL(HR_TABLE_CREATE);
Log.e("smartdbhelper", "after creation");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public SmartDBHelper open() throws SQLException
{
dBH = getWritableDatabase();
return this;
}
public long insertTitle(String isbn, String title, String publisher)
{
ContentValues initialValues = new ContentValues();
initialValues.put("hr", isbn);
initialValues.put("act", title);
initialValues.put("timestamp", publisher);
Log.e("insertes","i");
dBH.insert(HR_TABLE_NAME, null, initialValues);
return 11111111;
}
public Cursor getAllTitles()
{
return dBH.query(HR_TABLE_NAME, new String[] {
"hr","act","timestamp"},null,
null,
null,
null,
null);
}
//---closes the database---
public void close()
{
close();
}
}
The above code works and has been tested

Related

Difficult to store Shared preferences value to SQLIte in Android and having null value stored

I think i ran out from ideas about how to do this. I am building and TODO app with register and login feature. Once a user is logged, can create new todos task in SQLite(for now), later i want to delete and rename todos as well.
This is my DB class with SQliteHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id"; //autoincrement
private final static String user_Id = "userId";
private final static String TITLE = "title";
private final static String CONTENT = "content";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" +
")";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_mTODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
Adding new Task to second table
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(ctx);
// String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
// values.put(user_Id,todoTask.getUserID(d));
// Inserting Row
db.insert(mTODO, null, values);
db.close();
}
ToDo.java
public class ToDo {
private int id;
private String userID;
private String title;
private String content;
public ToDo(String content, int id, String title, String userID) {
this.content = content;
this.id = id;
this.title = title;
this.userID = userID;
}
public ToDo(String content, String title, String userID) {
this.content = content;
this.title = title;
this.userID = userID;
}
public ToDo() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId(String name) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserID(String userID) {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Add activity class with inputs and add method
public class addTask extends AppCompatActivity {
private EditText titleUser;
private EditText contentDesc;
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
Button btnAdd = (Button) findViewById(R.id.addToDo);
titleUser = (EditText) findViewById(R.id.titleID);
contentDesc = (EditText) findViewById(R.id.contentDescId);
db = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddItem();
}
});
}
private void AddItem() {
ToDo todo = new ToDo();
todo.setTitle(titleUser.getText().toString().trim());
todo.setContent(contentDesc.getText().toString().trim());
db.add(todo);
finish();
}
The current user that is logged, i am putting that user id to Shared preferences
In my second Table i have something like this
task_Id user_id title content
1 null Eat go to Mc
user_id is null here, and i don't know why
i want something like this
task_Id user_id title content
1 2 Eat go to Mc
user_id- should be which user id make the todo
Supposing that you already know how to store and get the userid from the shared preferences.
In your addTask activity, add:
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
userId = sharedPreference.getString("USER_ID",null);
...
}
in the addItem() add:
private void AddItem() {
...
todo.setUserId(userId);
...
}
in the DB add() use this:
public void add(ToDo todoTask) {
...
values.put(USERID, todoTask.getUserId());
...
}
OR:
Another approach is to get the value directly from the DB class if you are sure that you will never insert task for other users.
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
values.put(user_Id,todoTask.getUserID(d));
db.insert(mTODO, null, values);
db.close();
}
and in the constructor save the context for further use.
private Context ctx;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
You are creating ToDo Table using user_id. while static String refrenced is userid: hence in database when entered it goes null by default
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id";
private final static String user_Id = "userId"; //<----Wrong Here
private final static String TITLE = "title";
private final static String CONTENT = "content";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
Also here is something more for you, Simply you must supply the User Id value to the Field. Below are Some Examples How to do So
private static final String TAG = "DB_HANDLER";
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "ElmexContactsManager.db";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
private static final String TABLE_BIZ_SEGMENT = "BizSegment";
/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId";
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId";
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment";
/*04*/private static final String KEY_ADDED_ON = "AddedOn";
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "("
/*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
/*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER,"
/*03*/ + KEY_BIZ_SEGMENT + " TEXT,"
/*04*/ + KEY_ADDED_ON + " TEXT,"
/*05*/ + KEY_UPDATED_ON + " TEXT"
+ ")";
public ContactDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { try {
sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET);
} catch (SQLException e) {
e.printStackTrace();
}
Log.d(TAG, "Table Craeted ");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Drop older table if existed
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET);
// Create tables again
onCreate(sqLiteDatabase);
Log.d(TAG, "Table Udgraded to Version :" + i1);
}
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
public void addBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values);
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public void updateBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
//values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())});
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public List<BizSegment> getBizSegmentAll() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
List<BizSegment> bizSegmentList = new ArrayList<BizSegment>();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
try {
BizSegment bizSegment = new BizSegment(cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2),
df.parse(cursor.getString(3)),
df.parse(cursor.getString(4)));
bizSegmentList.add(bizSegment);
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
//2nd argument is String containing nullColumnHack
return bizSegmentList;
}
public void deleteBizSegment(BizSegment bizSegment) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?",
new String[]{String.valueOf(bizSegment.getBizSegmentId())});
db.close();
}
Other method is Using Shared Preference suitable for limited Data. It does not provide any relationships. I use this to store basic User related Data. Not for complicated/Relational Large Data. For That Sqlite is preferred.
public class AppPreference {
SharedPreferences pref;
SharedPreferences.Editor edit;
/**
* #param clientMaster object to set preference
* #param context Context of call
*/
public void putPreference(ClientMaster clientMaster, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putInt("ClientId", clientMaster.getClientId());
edit.putString("FirstName", clientMaster.getFirstName());
edit.putString("LastName", clientMaster.getLastName());
edit.putString("Mobile", clientMaster.getMobile());
edit.putInt("PincodeId", clientMaster.getPincodeId());
edit.putString("Email", clientMaster.getEmail());
edit.putString("Password", clientMaster.getPassword());
edit.putString("MembershipCode", clientMaster.getMembershipCode());
edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString());
edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString());
edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString());
edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode());
edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID());
edit.putInt("ReferredByID", clientMaster.getReferredByID());
//edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString());
edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode());
edit.putString("AddedOn", clientMaster.getAddedOn().toString());
//edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString());
edit.putBoolean("Login", true);
edit.putBoolean("Skip", false);
edit.commit();
}
/**
*
* #param appLanguage
* #param context
*/
public void putLanguagePreference(String appLanguage, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("AppLanguage", appLanguage);
edit.commit();
}
/**
* To clear All Object preference & Login False
*
* #param context Context call
*/
public void clearPreference(Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.clear();
edit.putBoolean("Login", false);
edit.commit();
}
/**
* #param InstanceId Instance Id
* #param context
*/
public void putPreferenceInstance(String InstanceId, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("InstanceId", InstanceId);
edit.commit();
}
}

SQLite database is not being created and no error coming

SQLite database is not being created while no error coming.
I have checked the android/data folder trying many things. I am using eclipse. Someone kindly help me and thanks in advance.
My Database.java file is this:
public class Database extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Table.db";
public static final String TABLE_NAME="table_one";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="SURNAME";
public static final String COL_4="MARKS";
public Database(Context context) {
super(context, TABLE_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg) {
// TODO Auto-generated method stub
arg.execSQL("create table "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase arg, int arg1, int arg2) {
// TODO Auto-generated method stub
arg.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(arg);
}
public boolean insert(String name, String sname, String marks)
{
SQLiteDatabase arg=this.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(COL_2, name);
content.put(COL_3, sname);
content.put(COL_4, marks);
long result=arg.insert(TABLE_NAME, null, content);
if(result==-1)
return false;
else
return true;
}
}
MainActivity.java is:
public class MainActivity extends Activity {
Database myDb;
EditText name, sname, marks;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new Database(this);
name = (EditText) findViewById(R.id.ename);
sname = (EditText) findViewById(R.id.esname);
marks = (EditText) findViewById(R.id.emarks);
add = (Button) findViewById(R.id.button1);
addData();
}
public void addData() {
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean isInserted = myDb.insert(name.getText().toString(), sname.getText().toString(), marks.getText().toString());
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data is inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data is NOT inserted", Toast.LENGTH_LONG).show();
}
});
}
#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;
}
}
public Database(Context context)
{
super(context, DATABASE_NAME , null, 1); // Your Mistake
}
Create your table like this :
String CREATE_TABLE = "CREATE TABLE " + GROUP_CHAT_MESSAGE_TABLE_NAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ SURNAME + " TEXT ,"
+ MARKS + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
Try taking a look here . You should however use a DAO class ; so you can manage information from the database and to it ,through an intermediate object.
Try creating the table like this :
private static final String DATABASE_CREATE = "create table "
+ DATABASE_NAME + "(" + COL_1 +
" integer primary key autoincrement, " +
COL_2 + " text not null, " + COL_3 + " text not null, " + COL_4 + " integer);";

cant able to insert the values in to SQLite. got null pointer exception

I was tried to insert some values to my SQLite database. like(id,name,number and image).but i got a null pointer exception while run the code. the values is display in the pojo class while i print using sys out. i dont know what is the problem here. please help me. Thanks in advance.
my code is here
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
picture = data.get(position);
listModelData.setTitle(String.valueOf(a[position]));
listModelData.setImageUrl(picture._image);
listModelData.setitemName(itemname);
listData.add(listModelData);
((MainActivity) context).getData(listData);
}
});
/////////////////////////////////////////////
public class MainActivity extends Activity {
ArrayList<ListModel> listData = new ArrayList<ListModel>();
HorizontalListView listview;
// HorizontalAdapter hAdapter;
HorizantalDBHandler hdb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (HorizontalListView) findViewById(R.id.listview);
// hAdapter = new HorizontalAdapter(getApplicationContext(), listData);
// listview.setAdapter(hAdapter);
}
public void getData(ArrayList<ListModel> listData) {
// TODO Auto-generated method stub
System.out.println("########DDDDDDDDD##########");
int id = 301;
String value = listData.get(0).getTitle();
String itemname = listData.get(0).getitemName();
byte[] image = listData.get(0).getImageUrl();
System.out.println(value);
System.out.println(image);
System.out.println(itemname);
System.out.println(id);
hdb.addContact(new HorizantalPojo(id, itemname, value, image));
System.out.println(value);
System.out.println(image);
System.out.println(itemname);
// hAdapter = new HorizontalAdapter(getApplicationContext(),listData);
// listview.setAdapter(hAdapter);
// hAdapter.notifyDataSetChanged();
}
}
///////////////////////////////////////////////////
public class HorizantalPojo {
// private variables
int _id;
public String _name;
public byte[] _image;
String _number;
// Empty constructor
public HorizantalPojo() {
}
// constructor
public HorizantalPojo(int id, String number, String name, byte[] image) {
System.out.println("it comessssssssss");
this._name = name;
this._image = image;
this._number = number;
this._id = id;
System.out.println(_id);
System.out.println(_name);
System.out.println(_image);
System.out.println(_number);
System.out.println("it comessssssssss");
}
// constructor
public HorizantalPojo(String name, byte[] image) {
this._name = name;
this._image = image;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting name
public String getName() {
return this._name;
}
// setting name
public void setName(String name) {
this._name = name;
}
// getting phone number
public byte[] getImage() {
return this._image;
}
// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
public String getNumber() {
return this._number;
}
// setting phone number
public void setNumber(String number) {
this._number = number;
}
}
/////////////////////////////////////////////////////
public class HorizantalDBHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "hrlist";
// Contacts table name
// private static final String TABLE_CONTACTS = "breakfast";
private static final String TABLE_BREAKFAST = "hrlist";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NUMBER = "number";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
public HorizantalDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_BREAKFAST_TABLE = "CREATE TABLE " + TABLE_BREAKFAST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_NUMBER + " TEXT," + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_BREAKFAST_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BREAKFAST);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public// Adding new contact
void addContact(HorizantalPojo contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
System.out.println("################");
System.out.println("################");
System.out.println("################");
System.out.println(contact._id);
System.out.println(contact._name);
System.out.println(contact._number);
System.out.println(contact._image);
values.put(KEY_ID, contact._id);
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_NUMBER, contact._number);
values.put(KEY_IMAGE, contact._image); // Contact Phone
//
//
// Inserting Row
db.insert(TABLE_BREAKFAST, null, values);
db.close(); // Closing database connection
}
// // Getting All Contacts
public List<HorizantalPojo> getAllContacts() {
List<HorizantalPojo> contactList = new ArrayList<HorizantalPojo>();
// Select All Query
String selectQuery = "SELECT * FROM hrlist ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HorizantalPojo contact = new HorizantalPojo();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// contact.setNumber(cursor.getString(3));
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println("^^^^^^^^^^^^^^^^");
System.out.println(cursor.getString(1));
System.out.println(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;
}
}
Your hdb=null
hdb=new HorizantalDBHandler(MainActivity.this);
initialized it before used. As seen your code.
hdb object of HorizantalDBHandler is null.
Initialize it before calling addContact method:
hdb=new HorizantalDBHandler(MainActivity.this);
hdb.addContact(new HorizantalPojo(id, itemname, value, image));

Android Sqlite java.lang.nullpointer exception

I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}

How to save database in Android?

I'm new to android development and I'm trying to make a simple application where i can add and view my records. I can successfully add data and view them in a table, it works ever time i run the program. (I'm following this tutorial) But every time i close Eclipse and try to add new data and view them, the previous information I entered was gone. it seems like when I close eclipse, it doesn't save my database. Here is the sample code I'm following.
package com.example.hotornot;
import java.sql.Statement;
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;
public class Example {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_NUM = "number";
public static final String DATABASE_NAME = "dbTry";
public static final String DATABASE_TABLE = "tblSamp";
public static final int DATABASE_VERSION = 1;
public DbHelper ourhelper;
public final Context ourcontext;
public SQLiteDatabase ourdatabase;
class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER, " + KEY_NAME + " NULL, " + KEY_NUM + " NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(arg0);
}
}
public Example(Context c)
{
ourcontext = c;
}
public Example open() throws SQLException
{
ourhelper = new DbHelper(ourcontext);
ourdatabase = ourhelper.getWritableDatabase();
return this;
}
public void close()
{
ourhelper.close();
}
public long createEntry(String name, String num)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_NUM, num);
return ourdatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID,KEY_NAME, KEY_NUM};
Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
for (c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +c.getString(iName) + " " + c.getString(iNum) + "\n";
}
return result;
}
}
You must be overwriting the existing database or uninstalling the app
please check your code
on Activity onCreate event check for the existence of db file if exist do not overwrite and skip the process definitely you will get the old records

Categories

Resources