db.insert function inserts only an auto incremented ID in the table and nothing else though I get values from activity edit texts. Rest of the cells of table row remain empty
Here is my code:
public class SHelper extends SQLiteOpenHelper {
static final String dbName = "School";
static final String studentTable = "Student";
static final String colName = "Name";
static final String colPassword = "Password";
public static final int dbVersion=1;
public SHelper(Context context)
{
super(context, dbName, null, dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+studentTable+"("+colID+" INTEGER PRIMARY KEY, "+colName+" TEXT,"+colPassword+" TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + studentTable);
onCreate(db);
}
public void add(StudentData studentdata)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(colName, StudentData.getName());
values.put(colPassword, StudentData.getPassword());
db.insert(studentTable, null, values);
db.close();
}
}
public class StudentData {
private static String name;
private static String password;
public StudentData() {
super();
}
public StudentData(String name,String password) {
super();
StudentData.name = name;
StudentData.password = password;
}
public static String getName() {
return name;
}
public void setName(String name) {
StudentData.name = name;
}
public static String getPassword() {
return password;
}
public void setPassword(String password) {
StudentData.password = password;
}
}
public class stoActivity extends Activity {
SHelper db = new SHelper(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sto);
final EditText fullname=(EditText)findViewById(R.id.fullName);
final EditText password=(EditText)findViewById(R.id.password);
final String fullname=fullname.getText().toString();
final String password=password.getText().toString();
Button registerbutton = (Button) findViewById(R.id.registerButton);
registerbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
db.add(new StudentData(fullname,password));
Intent it=new Intent(stoActivity.this,otherActivity.class);
stoActivity.this.startActivity(it);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_register, menu);
return true;
}
}
There's your issue:
public void add(*StudentData studentdata)
{
...
values.put(colName, *StudentData.getName());
values.put(colPassword, *StudentData.getPassword());
...
}
Can you see it? Your statement is referring to the wrong part of the signature. you need to change the StudentData in the body of your method to lower case studentdata to match what is being passed to the method as a parameter. This illegal behavior went by compiled because you have the static modifier in places where i'm not sure is necessary, ex. the getName() and getPassword() methods.
create table with AutoIncrement key, so change method onCreate to the following:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+studentTable+"("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+colName+" TEXT,"+colPassword+" TEXT);");
}
You are not inserting any value for the column you have declared as primary Key.
It´s just an assumtion, but I had similar problems if I wanted to save data inside db. In your onCreate-Method at db.execSQL, You got a blank after comma --> "INTEGER PRIMARY KEY, ". I know that SQLite is very sensitive with such kind of input, You have to look exactly at blanks, commas or any other input.
Related
In my app, I have a database with a table that contains several user made entries. Here's a simplified version of my SQLite database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "data.db";
public static final String TABLE_NAME = "log";
public static final String COL_1 = "ID"; //autoincrement in oncreate
...
public static final String COL_12 = "NUMBER"; //set through getCount()
public DatabaseHelper(Context context) {
...
}
#Override
public void onCreate(SQLiteDatabase db) {
...
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
...
}
public long getCount() {
...
}
public boolean insertData(...) {
...
}
public void update(long id, String param) {
...
}
public Cursor getAllData() {
...
}
//for when an entry is deleted and thus COL_12 numbering is not fixed
public void consolidate() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("ALTER TABLE log ORDER BY NUMBER ASC");
}
}
However, whenever I call myDb.consolidate(), my app crashes. From what I've read from other posts, this should work, but it only throws error code 1: missing database. Anyone know why? Any help is appreciated.
I am trying to make loging page but this code not run properly
application afer run tym says unfortunately has stopped i don't no why .i am new in android any one plzz help .i am so frustrate
database file!!
public class RegistrationDetailsDataBaseFile extends SQLiteOpenHelper {
public static final String DATABASE_NAME="registrationDataBase.db";
public static final String TABLE_NAME="registrationTable";
public static final String NAME="name";
public static final String PASSWORD="password";
public static final String PHONE="phone";
public static final String ADDRESS="address";
private static final String QUERY="CREATE TABLE "+TABLE_NAME+"(id integer primary key autoincrement"+NAME+"not null"+PASSWORD+"not null"+PHONE+"not null"+ADDRESS+"not null)";
RegistrationDetailsDataBaseFile(Context context){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db){
db.execSQL(QUERY);
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
db.execSQL("drop table if exists"+TABLE_NAME);
onCreate(db);
}
public void setName(String nam){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(NAME,nam);
db.insert(TABLE_NAME,null,contentValues);
db.close();
}
}
send data from this file file
public class MainActivity extends AppCompatActivity {
EditText mEditTextName,mEditTextPassword,mEditTextPhone,mEditTextAddress;
Button mButtonRegistration;
String getName,getPassword,getPhone,getAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditTextName=(EditText)findViewById(R.id.name);
mEditTextPassword=(EditText)findViewById(R.id.password);
mEditTextPhone=(EditText)findViewById(R.id.phone);
mEditTextAddress=(EditText)findViewById(R.id.address);
mButtonRegistration=(Button)findViewById(R.id.register);
mButtonRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getName=mEditTextName.getText().toString();
getPassword=mEditTextPassword.getText().toString();
getPhone=mEditTextPhone.getText().toString();
getAddress=mEditTextAddress.getText().toString();
RegistrationDetailsDataBaseFile objOfRegistrationDetailsDataBaseFile=new RegistrationDetailsDataBaseFile(getBaseContext());
objOfRegistrationDetailsDataBaseFile.setName(getName);
Toast.makeText(getBaseContext(), "name", Toast.LENGTH_LONG).show();
}
});
}
}
You didn't define any type of the columns. There is also spacing problems. To create table modify your query statement as following:
private static final String QUERY="CREATE TABLE "+TABLE_NAME+" (id integer primary key autoincrement, "+NAME+" TEXT NOT NULL, "+PASSWORD+" TEXT NOT NULL, "+PHONE+" TEXT NOT NULL, "+ADDRESS+"TEXT NOT NULL);";
Also modify the onUpgrade() method as following:
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
db.execSQL("drop table if exists "+TABLE_NAME);
onCreate(db);
}
I'm new to android. Here's one of my OnClickListeners. The thing is I don't know how to make it save when clicking the button. When I call createEventT(Event event), it says "non-static method cannot be referenced from a static context". Sometimes there's no error message, but the app crashes when clicking this button. Any ideas? Thanks.
OnClickListener:
OnClickListener doneT = new OnClickListener(){
#Override
public void onClick(View v) {
event.setTitle(inputToday.toString());
event.setYY(bearsCalendar.get(Calendar.YEAR));
event.setMM(bearsCalendar.get(Calendar.MONTH));
event.setDD(bearsCalendar.get(Calendar.DAY_OF_MONTH));
dateToday.setText(EventDBAdapter.createEventT(event));
}
};
And the event class:
public class Event {
int YY,MM,DD;
private String title;
public void setYY(int YY){this.YY=YY;}
public void setMM(int MM){this.MM=MM;}
public void setDD(int DD){this.DD=DD;}
public void setTitle(String title){this.title=title;};
public int getYY(){return YY;}
public int getMM(){return MM;}
public int getDD(){return DD;}
public String getTitle(){return title;}
}
public class EventDBAdapter{
private final Context mCtx;
static final String dbName="BearDatabase";
static final String eventTable="Events";
static final int dbVersion=1;
static final String colID="EventId";
static final String colTitle="Title";
static final String colDetails="Details";
static final String colYear="YY";
static final String colMonth="MM";
static final String colDay="DD";
static final String colHour="HH";
static final String colMinute="TT";
public DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
public EventDBAdapter(Context context){
mCtx=context;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context,dbName,null,dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+eventTable+" ("+colID+" INTEGER PRIMARY KEY , "
+colTitle+" TEXT NOT NULL , "+colDetails+" TEXT , "
+colYear+" INTEGER , "+colMonth+" INTEGER , "+colDay+" INTEGER , "
+colHour+" INTEGER , "+colMinute+" INTEGER );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + eventTable);
onCreate(db);
}
}
public EventDBAdapter open() throws SQLException{
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void upgrade(){
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
mDbHelper.onUpgrade(mDb, 1, 0);
}
public long createEventT(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
values.put(colYear,event.getYY());
values.put(colMonth, event.getMM());
values.put(colDay, event.getDD());
return mDb.insert(eventTable,null,values);
}
public long createEventI(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
return mDb.insert(eventTable,null,values);
}
}
Update:
Any problems in the database? After I made the changes, the whole thing crush.
change below to
dateToday.setText(EventDBAdapter.createEventT(event));
with below and it will work.
dateToday.setText(String.valueOf(EventDBAdapter.createEventT(event)));
I hope you are initializing event object before using it in onClick. if not, then initialize it like event = new Event(); before
event.setTitle(inputToday.toString());
Unless EventDBAdapter in your question is an instance of the EventDBAdapter class, then you are attempting to use a non-static method (public long createEventT()) in a static way (by accessing it through the class name).
To access it, you first need to create an instance of EventDBAdapter. One way to achieve this would probably be (assuming you are calling this method from inside an Activity):
long date = new EventDBAdapter(this).createEventT(event);
dateToday.setText(String.valueOf(date));
There are more answers on this topic here.
I am trying to insert data in the table MyProduct but every time i run the program it shows "null pointer exception" in db.insertData() in MainActivity and method insertData() in MyHelper class. Can anyone please tell me whats going wrong?? Thank You
MainActivity
public class MainActivity extends Activity {
MyHelper helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new MyHelper(this);
SQLiteDatabase sqLiteDatabase=helper.getWritableDatabase();
// helper.onCreate(sqLiteDatabase);
helper.insertData();
}
}
MyHelper.class
public class MyHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME="MyDatabase";
static final int DATABASE_VERSION=1;
static final String TABLE_NAME="MyCatalog";
static final String UID="ID";
static final String UTITLE="TITLE";
static final String UPRICE="PRICE";
static final String UDESCP="DESCP";
static final String CREATE_TABLE="CREATE TABLE"+TABLE_NAME+"("+UID+"VARCHAR(25) PRIMARY KEY,"+UTITLE+ " VARCHAR(255),"+UPRICE+" VARCHAR(255),"+UDESCP+" VARCHAR(255));";
private static final String DROP_TABLE="DROP TABLE" +TABLE_NAME+"IF EXISTS";
private Context context;
public MyHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context=context;
Message.message(context,"Constructor called");
}
public void onCreate(SQLiteDatabase db)
{
Message.message(context,"on create");
db.execSQL(CREATE_TABLE);
Message.message(context,"table created");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
Message.message(context,"upgrade called");
db.execSQL(DROP_TABLE);
onCreate(db);
}
ContentValues contentValues;
public SQLiteDatabase db;
public void insertData()
{
contentValues.put(UID,"W");
contentValues.put(UTITLE,"w");
contentValues.put(UPRICE,"10");
contentValues.put(UDESCP, "abc");
db.insert(TABLE_NAME, null, contentValues);
}
}
You haven't initialized your db or contentValues objects. At the start of your insertData method, try putting the following:
db = getWriteableDatabase();
contentValues = new ContentValues();
Hi I am new to android and I want to know how I can add buttons to my app programmatically . Actually the scenario is like this: In my app, I am having several default categories(given as buttons) to save data. I must provide an option add categories. When I click on the add categories button I must get an option to specify the category name and the sub category name(which i can do). But the thing is that I must get a new button with the entered name and it should not get deleted when i leave the application. Any help is highly appreciated.
To create database: refer How do I create a database in android?
Then you need to use DatabaseHelper class to insert,update or delete data on your database.
refer http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Now you must be able to manage your data using DatabaseHelper class's object in your activity.
1.DatabaseCreator.java
public class DatabaseCreator extends SQLiteOpenHelper{
private static final String DB_NAME="database_name";
private static final int DB_VER=1;
private static final String TABLE_NAME="create table table_name(_id integer primary key autoincrement,field1 text not null,field2 text not null)";
public DatabaseCreator(Context context)
{
super(context,DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_NAME);
}
#Override
public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {
database.execSQL("DROP TABLE IF EXISTS table_name");
onCreate(database);
}
}
2.DatabaseHelper.java
public class DatabaseHelper
{
public static final String TABLENAME_DB="table_name";
public static final String KEY_ID="_id";
public static final String KEY_FIELD1="field1";
public static final String KEY_FIELD2="field2";
Context context;
SQLiteDatabase sqdb;
DatabaseCreator dbcreator;
public DatabaseHelper(Context context)
{
this.context=context;
}
public DatabaseHelper open() throws SQLException
{
dbcreator=new DatabaseCreator(context);
sqdb=dbcreator.getWritableDatabase();
return this;
}
public void close()
{
dbcreator.close();
}
public long addItem(String field1,String field2)
{
ContentValues values=new ContentValues();
values.put(KEY_FIELD1,field1);
values.put(KEY_FIELD2,field2);
return sqdb.insert(TABLENAME_DB,null,values);
}
public long deletItem(long _id)
{
return sqdb.delete(TABLENAME_DB, "_id="+_id,null);
}
}
Use this in your activity like:
DatabaseHelper db_helper=new DatabaseHelper(getApplicationContext());
db_helper.open();
db_helper.addItem("field1_value","field2_value");
db_helper.close();