Inserting data in database in android - android

I am working in android , and trying to insert values in database, here is the code of my database class
public class DataHandler {
public static final String fname="fname";
public static final String lname="lname";
public static final String age="21";
public static final String height="180";
public static final String weight="50";
public static final String TABLE_NAME="user";
public static final int DATABASE_VERSION=1;
public static final String DATA_BASE_NAME="SLIMART_DATABASE";
public static final String TABLE_CREATE ="create table user(fname text not null, lname text not null, age text not null, height text not null,weight text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx=ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS user");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(String afname,String alname,String aage,String aheight,String aweight)
{
ContentValues content =new ContentValues();
content.put(fname,afname);
content.put(lname,alname);
content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData()
{
return db.query(TABLE_NAME,new String[] {fname,lname,age,height,weight},null,null,null,null,null);
}
}
and here is the activity code from where I am accessing the database class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
save=(Button) findViewById(R.id.button1);
fname=(EditText) findViewById(R.id.fname);
lname=(EditText) findViewById(R.id.lname);
age=(EditText) findViewById(R.id.age);
height=(EditText) findViewById(R.id.height);
weight=(EditText) findViewById(R.id.weight);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
String sfname=fname.getText().toString();
String slname=lname.getText().toString();
String sage=age.getText().toString();
String sheight=height.getText().toString();
String sweight=weight.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(sfname, slname, sage, sheight, sweight);
Toast.makeText(getBaseContext(),"Data Successfully Saved",Toast.LENGTH_LONG).show();
handler.close();
}
});
}
but I recieve this error in logcat
03-22 03:16:37.060: E/AndroidRuntime(1115): android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO user(lname,0,fname) VALUES (?,?,?)

content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
public static final String age="21";
public static final String height="180";
public static final String weight="50";
age, height and weight are not column names in your table but just numeric literals. Use actual column names as content keys. Also, you cannot have column names that are just numbers.
For example, change to:
content.put("age",aage);
content.put("height",aheight);
content.put("weight",aweight);

I checked your code & i saw the problem, this is your code to insert data.
public long insertData(String afname,String alname,String aage,String aheight,String aweight)
{
ContentValues content =new ContentValues();
content.put(fname,afname);
content.put(lname,alname);
content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
return db.insertOrThrow(TABLE_NAME, null, content);
}
-> Where: fname , lname , age, weight , height is field's name in database table. But you also define :
public static final String fname="fname";
public static final String lname="lname";
public static final String age="21";
public static final String height="180";
public static final String weight="50";
--> age,height , weight is not the name of field when you created database table.
SO: Please changed like this:
public static final String fname="fname";
public static final String lname="lname";
public static final String age="age";
public static final String height="height";
public static final String weight="weight";

Related

how to display sqllite inserting data using recyclerview in android studio

I am new to android.
When I insert data it works properly. but while I click the button for displaying the inserted data using recyclerview it makes following error message: Sqlite Insert and View has stopped.
Error message is like:
at
com.example.sqliteinsertandview.MainActivity.ShowData(MainActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
MainActivity code:
public class MainActivity extends AppCompatActivity {
private EditText nameEt, ageEt;
private Button insertBtn;
String name, age;
DatabaseHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
insertData();
}
private void insertData() {
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEt.getText().toString();
age = ageEt.getText().toString();
long id = helper.insertData(name, age);
Toast.makeText(MainActivity.this, "Your id" + id, Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
nameEt = findViewById(R.id.nameEt);
ageEt = findViewById(R.id.ageEt);
insertBtn = findViewById(R.id.insertBtn);
helper = new DatabaseHelper(this);
}
public void ShowData(View view) {
startActivity(new Intent(this, ShowActivity.class));
}
}
ShowActivity Code:
public class ShowActivity extends AppCompatActivity {
RecyclerView recyclerView;
UserAdapter adapter;
List<User> users;
DatabaseHelper helper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
init();
getData();
}
private void getData(){
Cursor cursor = helper.showData();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(helper.COL_ID));
String name = cursor.getString(cursor.getColumnIndex(helper.COL_NAME));
String age = cursor.getString(cursor.getColumnIndex(helper.COL_AGE));
users.add(new User(id,name,age));
adapter.notifyDataSetChanged();
}
}
private void init(){
recyclerView = findViewById(R.id.userRecyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
users = new ArrayList<>();
helper = new DatabaseHelper(this);
adapter = new UserAdapter(users);
recyclerView.setAdapter(adapter);
}
DatabaseHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "User.db";
private static String TABLE_NAME = "User";
public static String COL_ID = "Id";
public static String COL_NAME = "Name";
public static String COL_AGE = "Age";
private static int VERSION = 1;
private static String createTable = "create table "+TABLE_NAME+"(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
long insertData(String name, String age){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME,name);
contentValues.put(COL_AGE,age);
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
long id = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
sqLiteDatabase.close();
return id;
}
public Cursor showData(){
String show_all = " select* From "+TABLE_NAME;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(show_all,null);
return cursor;
}
}
You didn't add ShowActivity class in AndroidManifest.xml file. Add this inside application tag
<activity android:name=".ShowActivity"/>

Data repeating on restarting App in Android Database

I am facing this problem whenever i run the app 1st time data in database remain single time but when i close the App and restart again data goes twice(means two same row in table).Similarly for 3rd, 4th time and so on. How do i get rid of this problem? I even put datas.clear in DataList.java but don't whether i have add the datas.clear() line in correct place or not.
PLz help if there is any other problem in my code.
MainActivity.java code
public class MainActivity extends AppCompatActivity {
Button listButton, addButton;
DatabaseHelper df;
private final static String TAG = "TestActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
df = new DatabaseHelper(this);
addButton = (Button) findViewById(R.id.addbutton);
uploadList();
}
public void uploadList(){
DatabaseHelper df=new DatabaseHelper(this);
df.open();
try{
InputStream im=getResources().getAssets().open("testdata.csv");
BufferedReader br=new BufferedReader(new InputStreamReader(im));
String data=br.readLine();
while(data != null){
String t[]=data.split(",");
Product p=new Product();
p.setFirst(t[0]);
p.setSec(t[1]);
p.setThird(t[2]);
df.insert(p);
data=br.readLine();
}
}catch(Exception e){
}
}
}
DatabaseHelper.java code
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String FIRST="Name";
private static final String SECOND="Issn";
private static final String THIRD="ImpactFactor";
private static final String DATABASE="journal2016";
private static final String TABLENAME="journal";
private static final int VERSION=1;
SQLiteDatabase sd;
public void open(){
sd=getWritableDatabase();
}
public void close(){
sd.close();
}
public DatabaseHelper(Context context) {
super(context, DATABASE, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
sqLiteDatabase.execSQL("CREATE TABLE " + TABLENAME + " ( NAME TEXT, ISSN TEXT, IMPACTFACTOR REAL)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
}
public long insert(Product p){
ContentValues cv=new ContentValues();
cv.put(FIRST, p.getFirst());
cv.put(SECOND, p.getSec());
cv.put(THIRD, p.getThird());
return sd.insertWithOnConflict(TABLENAME, null, cv,SQLiteDatabase.CONFLICT_REPLACE);
}
public List<Product> getAllProduct(){
ArrayList<Product> list=new ArrayList<Product>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c=db.rawQuery("SELECT * FROM " + TABLENAME, null);
while(c.moveToNext()){
Product p=new Product();
p.setFirst(c.getString(0));
p.setSec(c.getString(1));
p.setThird(c.getString(2));
list.add(p);
}
db.close();
return list;
}
}
DataList.java code
public class DataList extends Activity{
List<Product> datas = new ArrayList<Product>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datas.clear();
DatabaseHelper d=new DatabaseHelper(this);
d.open();
datas = d.getAllProduct();
ListView lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas));
}
}
Product.java
public class Product {
private String first;
private String second;
private String third;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSec() {
return second;
}
public void setSec(String sec) {
this.second = sec;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
#Override
public String toString() {
return first + second + third;
}
}
Remove this line from your onCreate() method:
df = new DatabaseHelper(this);
as no need of it because you are create object of your DatabaseHelper class inside uploadList() method.
And also you are calling uploadList() method inside onCreate() thats why every time you launch the app, the onCreate() method executes and you uploadList() also execute. Try to put its calling statement in an onClickListener so it happens when you click a button or your choice of stuff.

Populating Listview from Database Only Works Once

I'm trying to update a listview with user entries into two text inputs. Once the save button is clicked, the user's entry should appear. Based on my code, the listview updates the first time I fill out the two text inputs and I hit save, but the second time I hit save, the listview does not update. Here's my code:
Home.java
public class Home extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText inputOne;
EditText inputTwo;
MyDBHandler dbHandler;
Button saveButton;
MyCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
inputOne = (EditText) findViewById(R.id.inputOne);
inputTwo = (EditText) findViewById(R.id.inputTwo);
dbHandler = new MyDBHandler(this, null, null, 1);
saveButton = (Button) findViewById(R.id.saveButton);
MyDBHandler myDBHandler = new MyDBHandler(this);
Cursor c = myDBHandler.getCursor();
cursorAdapter = new MyCursorAdapter(this,c,1);
ListView notes = (ListView) findViewById(R.id.notes);
notes.setAdapter(cursorAdapter);
public void saveClicked(View view) {
Test test = new Test( inputOne.getText().toString(), inputTwo.getText().toString() );
dbHandler.addTest(test);
inputOne.setText("");
inputTwo.setText("");
cursorAdapter.notifyDataSetChanged();
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Database.db";
public static final String TABLE_TEST = "test";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_ONE = "one";
public static final String COLUMN_TWO = "two";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TEST + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_ONE + " TEXT," +
COLUMN_TWO + " TEXT" + ");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
public void addTest(Test test){
ContentValues values = new ContentValues();
values.put(COLUMN_ONE, test.get_one());
values.put(COLUMN_TWO, test.get_two());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TEST, null, values);
db.close();
}
public Cursor getCursor(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_ACTIVITIES + " WHERE 1";
Cursor c = db.rawQuery(query, null);
return c;
}
}
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 1);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.custom_row, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView one = (TextView) view.findViewById(R.id.one);
TextView two = (TextView) view.findViewById(R.id.two);
String one_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_ONE));
one.setText(one_string);
String two_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_TWO));
two.setText(two_string);
}
}
Test.java
public class Test {
private int _id;
private String _one;
private String _two;
public Test(){
}
public Test(int id){
this._id = id;
}
public Test(String one, String two){
this._one = one;
this._two = two;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_one() {
return _one;
}
public void set_one(String _one) {
this._one = _one;
}
public String get_two() {
return _two;
}
public void set_two(String _two) {
this._two = _two;
}
The correct way to refresh a ListView backed by a Cursor is to call cursorAdapter.notifyDatasetChanged(), without needing to recreate and reset the adapter.
So in your saveClicked method you just update the db and let the Adapter know there has been a change.
To do this, you'll need to keep a reference to the adapter as an instance field instead of declaring it as a local variable.
Turns out my ListView was populating, but I made the mistake of putting a ListView inside of a ScrollView - so I wasn't able to see the addition of entries. It worked once I used the solution from this: Android - ListView's height just fits 1 ListView item

sqlite. Table not creating

I'm trying to create table in the sqlite, but it is showing error that table cannot be created. I have a same code but the database and table name are different. the fields are same. Also one doubt. Can't i create the different table in the same database containing the same fields.
DbAdapter.java
the code is as below.
public class DbAdapter {
private static final String DATABASE_NAME="bible1";
private static final String DATABASE_TABLE="test1";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID="_id";
public static final String UNITS="units";
public static final String CHAPTERS="chapters";
private static final String CREATE_DATABASE="create table test1 (_id integer primary key autoincrement, units text not null, chapters text not null);";
private SQLiteHelper sqLiteHelper;
private static SQLiteDatabase sqLiteDatabase;
private Context context;
//constructor
public DbAdapter(Context c){
context = c;
}
private static class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DATABASE);
MakeUnits();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DbAdapter open() throws SQLException{
try{
sqLiteHelper = new SQLiteHelper(context);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}catch(NullPointerException ne){
Log.e("error in creating the table", "bye");
}
return this;
}
public void close(){
sqLiteHelper.close();
}
public static long MakeUnits()
{
ContentValues insert1 = new ContentValues();
insert1.put(UNITS, "Unit1");
insert1.put(CHAPTERS, "CHAPTER1");
return sqLiteDatabase.insert(DATABASE_TABLE,null,insert1);
}
public Cursor fetchAllNotes(){
return sqLiteDatabase.query(DATABASE_TABLE, new String[]{KEY_ID,UNITS,CHAPTERS}, null, null, null, null, null);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private DbAdapter Database;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listContent = (ListView) findViewById(android.R.id.list);
Database= new DbAdapter(this);
Database.open();
Cursor c = Database.fetchAllNotes();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It is giving error when the open() method is called. Couldn't figure it out.
in the logcat the error in the tag is that "error in creating the table"
You're trying to call sqLiteDatabase.insert inside MakeUnits, but this sqLiteDatabase variable is null until after you call getWritableDatabase. You should pass db to MakeUnits and call insert on db, not on sqLiteDatabase.
database will be created only when you make a call to
getWritableDatabase()/getReadableDatabase()
If you do not have permissions for a writable db, you will get a readable
db.
public SQLiteDatabase getWritableDB() {
try {
return helper.getWritableDatabase();
} catch (Exception e) {
return getReadableDB();
}
}
public SQLiteDatabase getReadableDB() {
return helper.getReadableDatabase();
}

Unable to bind data by query from DB to spinner

Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
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)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}

Categories

Resources