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);";
Related
I am a student and started working on android studio recently. I don't know about it much. I am working on an application where I save the item name and its amount in the database and display toast message if data we entered is saved or not. problem is whenever I click on the save button my application crashes.
following is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Items.db";
public static final String TABLE_NAME = "item_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "ITEM";
public static final String COL_3 = "AMOUNT";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "ITEM TEXT, AMOUNT TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,item);
contentValues.put(COL_3,item);
long result = db.insert(TABLE_NAME,null, contentValues);
if(result == -1){
return false;
}else {
return true;
}
}
}
following is my MainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editItem, editAmount;
Button buttonSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editItem = (EditText)findViewById(R.id.item_field);
editAmount = (EditText)findViewById(R.id.amount_field);
buttonSave = (Button)findViewById(R.id.button_save);
AddData();
}
public void AddData(){
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editItem.getText().toString();
String amount = editAmount.getText().toString();
boolean insertData = myDb.addData(item, amount);
if(insertData == true){
Toast.makeText(MainActivity.this,"Amount is saved with Item detail", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Error occurred : Detailed are not saved", Toast.LENGTH_LONG).show();
}
}
});
}
}
I will appreciate your help.
Thank you
It might be crashing because it's not creating the table:
String createTable = "CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "ITEM TEXT, AMOUNT TEXT)";
A space is missing between table and its name:
String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEM TEXT, AMOUNT TEXT)";
You should also close the database after you get the data in db.insert but this only creates a warning:
long result = db.insert(TABLE_NAME,null, contentValues);
db.close();
im getting problem in displaying my data from sqlite db
my apps stops working when run and display no errors.
please help me
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ExpDatee.db";
public static final String TABLE_NAME = "EXPDATE_TABLE";
public static final String COL_1 = "PRO_ID";
public static final String COL_2 = "PRO_NAME";
public static final String COL_3 = "PRO_EXPDATE";
public static final String COL_4 = "PRO_DAYTILLEXP";
/**
private static final String SQL_CREATE_TABLE_EXPDATE = "CREATE TABLE " + TABLE_NAME + "("
+ PRO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PRO_NAME + " TEXT NOT NULL, "
+ PRO_EXPDATE+ " TEXT NOT NULL, "
+ PRO_DAYTILLEXP + " TEXT NOT NULL, "
+ ");";
**/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(PRO_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"PRO_NAME TEXT, " +
"PRO_EXPDATE TEXT," +
" PRO_DAYTILLEXP TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
//method to insert data
public boolean insertData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,PRO_NAME);
contentValues.put(COL_3,PRO_EXPDATE);
contentValues.put(COL_4,PRO_DAYTILLEXP);
Log.d(TAG, "ADD DATA : ADDING " + PRO_NAME + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_EXPDATE + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_DAYTILLEXP + " TO " + TABLE_NAME);
long result = db.insert(TABLE_NAME,null ,contentValues );
if (result == -1)
return false;
else
return true;
}
//get all data
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM" + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etProductName, etDaysBeforeExp, etExpDate;
Button btnAddItem, btnViewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etProductName = (EditText)findViewById(R.id.etProductName);
etDaysBeforeExp = (EditText)findViewById(R.id.etDaysBeforeExp);
etExpDate = (EditText)findViewById(R.id.etExpDate);
btnAddItem = (Button)findViewById(R.id.btnAddItem);
btnViewItem = (Button)findViewById(R.id.btnViewItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PRO_NAME = etProductName.getText().toString();
String PRO_EXPDATE = etExpDate.getText().toString();
String PRO_DAYTILLEXP = etDaysBeforeExp.getText().toString();
if(etProductName.length() !=0)
{
AddData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
etProductName.setText("");
etExpDate.setText("");
etDaysBeforeExp.setText("");
}
else
{
toastMessage("PLEASE INSERT VALUE");
}
}
});
btnViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
boolean InsertData = myDB.insertData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
if(InsertData)
{
toastMessage("DATA INSERTED");
}
else
{
toastMessage("DATA NOT INSERTED");
}
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
ListDataActivity.java
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper myDB;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
populateListView();
}
private void populateListView() {
Cursor data = myDB.getData();
ArrayList<String> listData = new ArrayList<>();
while (data.moveToNext())
{
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
Initialized Listdataactivity
myDB = new DatabaseHelper(this);
Use Arrayadapter
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
There is a problem with insetion in database. I don't know what to do.
It writes error inserting.
public class MainActivity extends Activity implements OnClickListener {
BaseOpener bo;
private static final String ML = "ML";
Button read, write;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
read = (Button) findViewById(R.id.read);
read.setOnClickListener(this);
write = (Button) findViewById(R.id.write);
write.setOnClickListener(this);
bo = new BaseOpener(this);
Log.i("Ml", "good start");
}
#Override
public void onClick(View v) {
SQLiteDatabase db = bo.getWritableDatabase();
switch (v.getId()) {
case R.id.write:
{
ContentValues cv = new ContentValues();
Log.i("ML", "write");
cv.put("id", 1);
cv.put("name", "Petr");
cv.put("phone", "911");
cv.clear();
db.insert("table1", null, cv);
}
break;
case R.id.read:
{`enter code here`
Log.i("ML", "read");
Cursor c = db.query("table1",null,null,null,null,null,null);
if(c.moveToFirst()){
int idColIndex = c.getColumnIndex("id");
int nameColIndex = c.getColumnIndex("name");
int emailColIndex = c.getColumnIndex("phone");
Log.i("ML",
"ID = " + c.getInt(idColIndex) +
", name = " + c.getString(nameColIndex) +
", phone = " + c.getString(emailColIndex));
}
}
break;
}
db.close();
Log.i("ML", "the base is closed");
}
}
public class BaseOpener extends SQLiteOpenHelper {
public BaseOpener(Context context) {
super(context, "contacts", null, 1);
Log.i("ML", "the base is ready");
}`enter code here`
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
clear()
Removes all values. Read more on ContentValues here
Your table lists id as primary key so you can't insert it twice. I would just comment out the cv.put("id",1) line and let sqlite handle it.
//cv.put("id", 1);
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
Also from your next app on consider naming your id column _id. This will make the table more compatible with cursor adapters and such.
Look at these links they all use _id
cursorAdapter ContentProvider ListView
I am making this sample app that will insert, update, delete and retrieve data from database. now the problem I am facing is how to update the record. I know I have to pass Id but how.
MainActivity.java :
public class MainActivity extends Activity {
Button btnSubmit, btnUpdate, btnDelete;
EditText UserName, FirstName, LastName, txtPassword;
RunDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new RunDatabase(this);
UserName = (EditText) findViewById(R.id.User_Name);
FirstName = (EditText) findViewById(R.id.First_Name);
LastName = (EditText) findViewById(R.id.Last_Name);
txtPassword = (EditText) findViewById(R.id.Password);
btnSubmit = (Button) findViewById(R.id.btn_Submit);
btnSubmit.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
addRow();
}
});
btnUpdate = (Button) findViewById(R.id.btn_Update);
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateRow();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void addRow()
{
try
{
db.addRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString()
);
// remove all user input from the Activity
emptyFormFields();
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
private void updateRow()
{
try
{
db.updateRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString()
);
emptyFormFields();
}
catch (Exception e)
{
Log.e("Update Error", e.toString());
e.printStackTrace();
}
}
private void emptyFormFields()
{
User_Id.setText("");
FirstName.setText("");
LastName.setText("");
UserName.setText("");
txtPassword.setText("");
}
}
RunDatabase.java:
public class RunDatabase {
Context context;
private SQLiteDatabase db; // a reference to the database manager class.
private final String DB_NAME = "Records"; // the name of our database
private final int DB_VERSION = 1; // the version of the database
// the names for our database columns
private final String TABLE_NAME = "tblRecords";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "UserName";
private final String TABLE_ROW_TWO = "FirstName";
private final String TABLE_ROW_THREE = "LastName";
private final String TABLE_ROW_FOUR = "Password";
// the beginnings our SQLiteOpenHelper class
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString =
"create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null, " +
TABLE_ROW_ONE + " text, " +
TABLE_ROW_TWO + " text, " +
TABLE_ROW_THREE + " text, " +
TABLE_ROW_FOUR + " text" +
");";
System.out.println(newTableQueryString);
// execute the query string to the database.
db.execSQL(newTableQueryString);
}
public RunDatabase(Context context)
{
this.context = context;
// create or open the database
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try
{
db.insert(TABLE_NAME, null, values);
}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace(); // prints the stack trace to the log
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION.
// OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE.
}
}
}
1. In your create table String,
String newTableQueryString =
"create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null, " +
TABLE_ROW_ONE + " text, " +
TABLE_ROW_TWO + " text, " +
TABLE_ROW_THREE + " text, " +
TABLE_ROW_FOUR + " text" +
");";
The ROW_ID is an integer, so in your function updateRow(), the data type for parameter of rowID should be integer, which is passed in the "where" clause. So should change
-> public void updateRow(long rowID, String rowStringOne,...
2. To identify the row you have added, you need to have a primary key which you will be able to identify on the basis of the entry.
Auto increment integer is good for ensuring that the database will have a new row each time,
but the primary key you need should be something you will know to differentiate entries.
Can try a derived key which would be another column in your db, to insert the same with adding rows would be like:
String customPrimaryKey="UserName.getText().toString()+FirstName.getText().toString()+txtPassword.getText().toString()";
db.updateRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString(),
// add one more value for a particular entry-a primary key for You to identify that row
customPrimaryKey
);
So you have a way to identify which row to update then, and pass the same in the updateRow() parameters for the where clause
You could try like this-
db.update(TABLE_NAME, values, TABLE_ROW_ID + "=?", String[]{rowID});
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