I tried to create a database and create one table in it. The database is being created but not the table.it doesn't show any error and also am not able to insert the value into it.I want to create a table and insert the data recieved from the user but the data is not able to add to database, neither it shows any errors.The code is as follows:
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE IF NOT EXISTS " + TABLE_NAMETRY + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT " + ")";`enter code here`
db.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP table if exist "+TABLE_NAMETRY);
onCreate(db);
}
public boolean insertData(String name,String no)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalue = new ContentValues();
contentvalue.put(COL_NAME,name);
contentvalue.put(COL_PHONE,no);
long result = db.insert(TABLE_NAMETRY,null,contentvalue);
if(result==-1)
return false;
else
return true;
}
public class MainActivity extends AppCompatActivity {
DataBaseHelper mydb;
EditText name,no;
Button b1;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new DataBaseHelper(this);
name=(EditText)findViewById(R.id.name);
no=(EditText)findViewById(R.id.no);
t1=(TextView)findViewById(R.id.t1);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Adding Data", Toast.LENGTH_SHORT).show();
AddData();
}
});
}
public void AddData()
{
boolean check= mydb.insertData(name.getText().toString(),no.getText().toString());
if(check==true)
t1.setText("data submitted");
else
t1.setText("data not submitted");
}
}
Most probably the helper is creating the table (onCreate) and then delete it (onUpgrade).
Here how I create my helper, take notice of the databaseVersion, as it is important when the (onUpgrade) is executed
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private final static String databaseName = "Your_DB_Name";
private final static int databaseVersion = 13;
DatabaseOpenHelper(Context context) {
super(context, databaseName, null, databaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) { // Do Create Your Table Here }
#Override
public void onUpgrade(SQLiteDatabase db, int Old_Version, int New_Version) { //Delete Your tables here if they exists}
Related
I have a program to sum two numbers and save result in SQL then show results in a TextView but I don't know how to make that; help me please.
But this number comes from the user (EditText) or from button ...
must I make a new table for the sum number for example or what .
I watch videos on you tube but I can do it that program.
this my code...
in DataBase activity :
public class DB_sql extends SQLiteOpenHelper {
public static final String name = "data.db";
public static final String TABLE_NAME="mydata";
public static final String KEY_First="first";
public static final String KEY_second="second";
public DB_sql(#Nullable Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table TABLE_NAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, KEY_First INTEGER, KEY_second INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
public boolean insertdata (int first,int second){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues numbers = new ContentValues();
numbers.put("first",first);
numbers.put("second",second);
long result = db.insert(TABLE_NAME,null,numbers);
if (result == -1)
return false;
else
return true;
}
in result activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView)findViewById(R.id.result);
int first = getIntent().getIntExtra("number1",0);
int second = getIntent().getIntExtra("number2",0);
Boolean dataSQL = db_sql.insertdata(first,second);
if (dataSQL == true){
Toast.makeText(this,"data inserted",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"data not inserted",Toast.LENGTH_SHORT).show();
}
in MainActivity:
public class MainActivity extends AppCompatActivity {
// DB_sql db_sql = new DB_sql(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void second(View view) {
Intent sec = new Intent(this,result.class);
sec.putExtra("number2",40);
startActivity(sec);
}
public void first(View view) {
Intent fir=new Intent(this,result.class);
fir.putExtra("number1",85);
startActivity(fir);
}
}
My table is not getting created in Sqlite (Toast for dataNotInserted).Code snippet below...
EXCEPTION
android.database.sqlite.SQLiteException: no such table: PETROL.DB (code 1): , while compiling: INSERT INTO PETROL.DB(AMOUNT) VALUES (?)
Activity2.java
public class Activity2 extends AppCompatActivity {
EditText ET1;
Button B1;
Button Bview;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
myDb = new DatabaseHelper(this);
ET1 = findViewById(R.id.editText_amount);
B1 = findViewById(R.id.button_add);
Bview = findViewById(R.id.button_view);
AddData();
}
public void AddData() {
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = myDb.insertData(Integer.parseInt(ET1.getText().toString()));
if (isInserted == true) {
Toast.makeText(Activity2.this, "DataInserted", Toast.LENGTH_LONG).show();
} else
Toast.makeText(Activity2.this, "DataNotInserted", Toast.LENGTH_LONG).show();
}
}
);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="PETROL.DB";
public static final String TABLE_NAME="PETROL_TABLE";
public static final String COL_1="ID";
public static final String COL_2="AMOUNT";
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL( "CREATE TABLE " + TABLE_NAME + "(" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_2 + " INTEGER );");
Log.d("data","ghgc");
}
public boolean insertData(int data)
{
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
ContentValues contextValues=new ContentValues();
contextValues.put("AMOUNT",data);
Log.d("insertData",Integer.toString(data));
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
if(result==-1)
return false;//to check if data is inserted
else
return true;
//sqLiteDatabase.close();
}
}
onUpgrade not mentioned since i'm still working on version 1
Your issue is as per the message and is caused as your are passing the Database name PETROL.DB to the insert method instead of passing the table name. As per the method's signature :-
long insert(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database. SQLiteDatabase - insert
As such change :-
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
to :-
long result= sqLiteDatabase.insert(TABLE_NAME,null,contextValues);
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I am new to Android SQLite database & while executing this.getWritableDatabase() my app stops. Is there any solution to this problem? My database is about getting students' information and saving their marks in the database.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Dictionary.db";
public static final String TABLE_NAME="Dictionary_data";
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 DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean insert_data(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
return false;
else
return true;
}
}
And my mainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText editName,editSurname,editMark;
Button btn_add_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this.getApplicationContext());
editName = (EditText)findViewById(R.id.namespace);
editSurname = (EditText)findViewById(R.id.surnamespace);
editMark = (EditText)findViewById(R.id.markspace);
btn_add_data = (Button)findViewById(R.id.add_button);
addData();
}
public void addData(){
btn_add_data.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean id_inserted = myDB.insert_data(editName.getText().toString(),editSurname.getText().toString(),editMark.getText().toString());
if(id_inserted)
Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
there is error in create table
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
please add space after TABLE
db.execSQL("CREATE TABLE "+ TABLE_NAME+ " (ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
also add log cat for more details,i am not able to comment as it's my new account.
On first activity user creates an object(A) after that Id + name of object(A) are saving in SQLite. When it saved user need to be forwarded to another activity but that activity need to have Id of object(A) which was created before. After that user will make some items insides the (object A). And when we go main activity and see list of objects(A) after pushing on item user will see all objects(B) which related to choosen object(A).
My code is
final String LOG_TAG = "myLogs";
Thread thread;
Button btnConfirmItemList;
EditText etName;
DBHelper dbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unit_list_item);
btnConfirmItemList = findViewById(R.id.add_list_btn_confirm);
btnConfirmItemList.setOnClickListener(this);
etName = findViewById(R.id.list_item_title);
dbHelper = new DBHelper(this);
}
#Override
public void onClick(View view) {
thread = new Thread(this, "Поток для примера");
Log.i(LOG_TAG, "Создан второй поток " + thread);
thread.start(); // Запускаем поток
}
#Override
public List<ListModel> addList(int id, String listName) {
return null;
}
#Override
public void run() {
try {
Log.i(LOG_TAG, " ------ Второй поток запущен ------ ");
ContentValues cv = new ContentValues();
String name = etName.getText().toString();
SQLiteDatabase db = dbHelper.getWritableDatabase();
if(btnConfirmItemList.isEnabled()){
cv.put("name", name);
long rowID = db.insert("mytable", null, cv);
Log.d(LOG_TAG, "row inserted, ID = " + rowID);
}
dbHelper.close();
Thread.sleep(500);
} catch (InterruptedException e) {
Log.i(LOG_TAG, " ------ Второй поток прерван ------ ");
}
}
class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "myDB", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(LOG_TAG, "--- onCreate database ---");
db.execSQL("create table mytable ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "email text" + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public int getItemIdByPosition() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query("mytable", null, null, null, null, null,
null);
if (c.moveToLast()) {
int idColIndex = c.getColumnIndex("id");
Log.d(LOG_TAG,"ID = " + c.getInt(idColIndex));
int idIndex = idColIndex;
return idIndex ;
} else
Log.d(LOG_TAG, "Id didnt selected");
c.close();
int idIndexx = idIndex;
return idColIndex;
}
}
}
I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}