Getting an error while creating new instance SQLITE - java

i have an error while making a creating a new instance for writing data to my database SQLlite
this is the code of my database class
package com.example.tttt;
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 info {
public static final String key_nom = "nom_personne";
public static final String key_id = "id_personne";
public static final String key_prenom = "prenom_personne";
private static final String DATABASE_NAME = "infodb";
private static final String DATABASE_TABLE = "infotable";
private static final int DATABASE_VERSION = 1 ;
private DbHelper ourHelper;
private Context ourContext ;
private SQLiteDatabase ourDatabase ;
private static 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 db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
key_id + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
key_nom + " TEXT NOT NULL, " +
key_prenom + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public info open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String prenom) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(key_nom, name);
cv.put(key_prenom, prenom);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
in my class activity i wrote
info entry = new info(this);
entry.open();
entry.createEntry(name , prenom );
entry.close();
i had a error on info entry = new info(this);
the message error : " The constructor info(new View.OnClickListener(){}) is undefined "
when i change to info entry = new info(intro.this);
i got: "The constructor info(intro) is undefined"
the full intro activity where i try get information from the user and send them to the database
package com.example.tttt;
import com.example.tttt.R.layout;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.DropBoxManager.Entry;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class intro extends Activity {
Button sqlupdate,sqlview,sqlsearch;
EditText sqlnom, sqlprenom,sqltextsearch ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
sqlnom = (EditText)findViewById(R.id.nomenter);
sqlprenom = (EditText)findViewById(R.id.prenomenter);
sqlupdate = (Button) findViewById(R.id.button1);
sqlview = (Button) findViewById(R.id.button2);
// sqlsearch = (Button) findViewById(R.id.button3);
// sqltextsearch = (EditText)findViewById(R.id.editText1);
sqlupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean diditwork = true ;
try{
String name = sqlnom.getText().toString();
String prenom = sqlprenom.getText().toString();
entry = new info();
entry.open();
entry.createEntry(name , prenom );
entry.close();
}catch (Exception e ){
diditwork = false ;
String error = e.toString();
Dialog d = new Dialog(intro.this);
d.setTitle(" merde ");
TextView tv = new TextView(intro.this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if (diditwork){
Dialog d = new Dialog(intro.this);
d.setTitle(" okkk ");
TextView tv = new TextView(intro.this);
tv.setText(" ok yes ");
d.setContentView(tv);
d.show();
}
}
}
});
sqlview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent open = new Intent("android.intent.action.SQLVIEW");
startActivity(open);
}
});
sqlsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
/*String s = sqltextsearch.getText().toString();
info se = new info();
se.open();
String returne = se.search();
*/
}
});
}
}

you have to initialize the info class without parameters:
info entry = new info();
btw. It is common in class names to write the first letter uppercase: Info
Furthermore. If you dont have more code in info your application will throw a NullPointerException here ourDatabase.insert(DATABASE_TABLE, null, cv);

Here in the Class Info there is no Constructor with an Argument of type Intro
Create one if you really need to have the instance of the class Intro at Class Info.
public Info(Intro intro){
}
Else Create a Constructor without any argument passed.
Info entry = new Info(this);
Always try to follow the naming Conventions, its not a good way to program in any way you like. http://www.oracle.com/technetwork/java/codeconv-138413.html

Related

Check if value entered exists in database android

I want to check if the Username&Password that the user entered exists in the database
I have tried this code, but i don't get it how to work with the cursor and what I'm doing wrong.
package com.example.nir.nestleapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class LoginActivity extends AppCompatActivity {
MyDBHandler Newdb;
private SQLiteDatabase _database = null;
private MyDBHandler _dbHelper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Newdb = new MyDBHandler(this);
_dbHelper = new MyDBHandler(getApplicationContext());
_database = this.openOrCreateDatabase(MyDBHandler.DATABASE_NAME, MODE_PRIVATE, null);
SQLiteDatabase database=_dbHelper.getReadableDatabase();
final ArrayList list = new ArrayList();
final TextView RegisterPage=(TextView)findViewById(R.id.textView4);
TextView Text1=(TextView)findViewById(R.id.textView3);
Button Login=(Button)findViewById(R.id.LoginBtn);
Button GuestLogin=(Button)findViewById(R.id.LoginGuestBtn);
final EditText LoginUser=(EditText)findViewById(R.id.LoginUser);
final EditText LoginPass=(EditText)findViewById(R.id.LoginPassword);
RegisterPage.setTextSize(17);
Text1.setTextSize(17);
RegisterPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
GuestLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,MainPageActivity.class));
}
});
Cursor c = database.rawQuery("SELECT * FROM " + MyDBHandler.Table_Name, null);
if (c == null) return;
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
list.add(c.getString(0));
list.add(c.getString(1));
c.moveToNext();
}
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(LoginUser.getText().toString().isEmpty()||LoginPass.getText().toString().isEmpty())
{
Toast.makeText(LoginActivity.this, "", Toast.LENGTH_SHORT).show();
}
if(list.contains(LoginUser.getText().toString())&&list.contains(LoginPass.getText().toString()))
{
Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
}
else
{
Toast.makeText(LoginActivity.this, "wrong", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is my DBHelper:
package com.example.nir.nestleapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UsersTable.db";
public static final String Table_Name = "UsersTable";
public static final String KEY_User = "User";
public static final String KEY_Password = "Password";
public static final String KEY_FullName = "FullName";
public static final String KEY_PhoneNumber="PhoneNumber";
public static final String KEY_IDNUMBER="IDNumber";
public static final String[] DB_COL = new String[]{KEY_User,KEY_Password,KEY_FullName,KEY_PhoneNumber,KEY_IDNUMBER};
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CreateTableSql = "Create Table " + Table_Name + " ( " +
KEY_User + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
KEY_Password + " TEXT , " +
KEY_FullName + " TEXT , "+
KEY_PhoneNumber+" TEXT , "+
KEY_IDNUMBER+ " ) ";
db.execSQL(CreateTableSql);
}#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table_Name);
onCreate(db);
}
public void Add(UserTable NewUser) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_User,NewUser.GetUserName() );
values.put(KEY_Password, NewUser.GetPassword());
values.put(KEY_FullName,NewUser.GetFullName());
values.put(KEY_PhoneNumber,NewUser.GetPhoneNumber());
values.put(KEY_IDNUMBER,NewUser.GetID());
db.insert(Table_Name, null, values);
db.close();
}
}
Updated LoginActivity
package com.example.nir.nestleapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
MyDBHandler Newdb;
private SQLiteDatabase _database = null;
private MyDBHandler _dbHelper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Newdb = new MyDBHandler(this);
_dbHelper = new MyDBHandler(getApplicationContext());
_database = this.openOrCreateDatabase(MyDBHandler.DATABASE_NAME, MODE_PRIVATE, null);
final TextView RegisterPage=(TextView)findViewById(R.id.textView4);
TextView Text1=(TextView)findViewById(R.id.textView3);
Button Login=(Button)findViewById(R.id.LoginBtn);
Button GuestLogin=(Button)findViewById(R.id.LoginGuestBtn);
final EditText LoginUser=(EditText)findViewById(R.id.LoginUser);
final EditText LoginPass=(EditText)findViewById(R.id.LoginPassword);
RegisterPage.setTextSize(17);
Text1.setTextSize(17);
RegisterPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
GuestLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,MainPageActivity.class));
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(LoginUser.getText().toString().isEmpty()||LoginPass.getText().toString().isEmpty())
{
Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
}
if(_dbHelper.getUserRow(LoginUser.getText().toString(),LoginPass.getText().toString())>0)
{
Toast.makeText(LoginActivity.this, "good!", Toast.LENGTH_SHORT).show();
HashMap<String,String> userInfo = _dbHelper.getUserInfo(LoginUser.getText().toString(),LoginPass.getText().toString());
Intent intent = new Intent(LoginActivity.this,MainPageActivity.class);
intent.putExtra("userInfo",userInfo);
startActivity(intent);
}
else
{
Toast.makeText(LoginActivity.this, "wrong", Toast.LENGTH_SHORT).show();
}
}
});
}
}
I think your problem is on your c.getString() in your whole loop. The first index should be ID and it might not be ID as well so the proper way is to using
c.getString(c.getColumnIndex("yourkey"));
Another tips try to not use rawQuery unless you really got no option. You could easily just do a check something like this.
Put this code inside your handler. It might have some syntax error you could try to fix it.
public int getUserRow(String username,String password){
SQLiteDatabase db = this.getReadableDatabase();
String[] column = {"id"};
Cursor cursor = db.query(handler.TABLE_USER,column,"User = ? AND Password = ?",new String[]{username,password},null,null,null);
int row = cursor.getCount();
return row;
}
When you check for login just simply so you don't have actually get the all user from the database to check wether this user is actually exists.
if(_dbHelper.getUserRow(yourUsername,yourPassword)){
//Login here
}
One more thing try to keep all database related code inside database class which it is very good pratice and you won't get any confusion after looking back the code.
Updated:
Here is the code when you wan to get the login user info add it inside your database helper as well you need to edit the column to match your column
public HashMap<String,String> getUserInfo(String username,String password){
HashMap<String,String> user = new HashMap<String,String>();
SQLiteDatabase db = this.getReadableDatabase();
String[] column = {"usernam","password","rest","of","your","key"};
Cursor cursor = db.query(handler.TABLE_USER,column,"User = ? AND Password = ?",new String[]{username,password},null,null,null);
int usernameIndex = cursor.getColumnIndex("username");
int passwordIndex = cursor.getColumnIndex("password");
int restIndex = cursor.getColumnIndex("rest");
int ofIndex = cursor.getColumnIndex("of");
int keyIndex = cursor.getColumnIndex("key");
if(cursor.getCount() > 0){
user.put("username",cursor.getString(usernameIndex));
user.put("password",cursor.getString(passwordIndex));
user.put("username",cursor.getString(restIndex));
user.put("of",cursor.getString(ofIndex));
user.put("key",cursor.getString(keyIndex));
}
return user;
}
So in your if statement try to add this. This code basically help you get user data and pass all the data to your user info activity.
if(_dbHelper.getUserRow(yourUsername,yourPassword)){
HashMap<String,String> userInfo = _dbHelper.getUserInfo(username,password);
Intent intent = new Intent(yourContext,YourActivity.class);
intent.putExtra("userInfo",userInfo);
startActivity(intent);
}
So now you pass all the data to the other activity you could grab it inside your onCreate.
userInfo = (HashMap<String, String>) getIntent().getSerializableExtra("userInfo");
Log.d("user",userInfo.get("your key"));

Why does Android Studio Keep Saying there is no title Column?

No matter how many times I've reviewed my code I keep getting a LogCat error of
Process: com.zito.zitolab4, PID: 2357
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zito.zitolab4/com.zito.zitolab4.ZitoLab4Data}: android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT id, title, genre, releaseYear FROM movies
Based on the LogCat I figured it would be in the Data.Java Class but I've looked everywhere and I'm just not setting it.I would appreciate any advice.
Thanks
Data.Java
package com.zito.zitolab4;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class ZitoLab4Data extends ActionBarActivity {
TextView idView;
EditText titleBox, genreBox, yearBox;
Button addMovieButton;
TableLayout movieTable;
private ZitoDataController sqlCon;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zito_lab4_data);
sqlCon = new ZitoDataController(this);
titleBox = (EditText) findViewById(R.id.movieTitle);
genreBox = (EditText) findViewById(R.id.movieGenre);
yearBox = (EditText) findViewById(R.id.releaseYear);
addMovieButton = (Button) findViewById(R.id.addMovieButton);
movieTable = (TableLayout) findViewById(R.id.movieTable);
BuildTable();
addMovieButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MyAsync().execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_zito_lab4_data, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void BuildTable() {
sqlCon.open();
Cursor dbCursor = sqlCon.readEntry();
int movies = dbCursor.getCount();
int fields = dbCursor.getColumnCount();
// 1 row for each person in the database table
for (int i = 0; i < movies; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
// create a TextView for each field in the record
for (int j = 0; j < fields; j++) {
TextView TableDataTextView = new TextView(this);
TableDataTextView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
TableDataTextView.setTextSize(16);
TableDataTextView.setPadding(0, 5, 0, 5);
TableDataTextView.setText(dbCursor.getString(j));
row.addView(TableDataTextView);
}
dbCursor.moveToNext();
movieTable.addView(row);
}
sqlCon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
movieTable.removeAllViews();
progressDialog = new ProgressDialog(ZitoLab4Data.this);
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String title = titleBox.getText().toString();
String genre = genreBox.getText().toString();
int year = Integer.parseInt(yearBox.getText().toString());
sqlCon.open();
sqlCon.insertData(title, genre, year);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
BuildTable();
progressDialog.dismiss();
titleBox.setText("");
genreBox.setText("");
yearBox.setText("");
titleBox.requestFocus();
}
}
}
DataModel.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ZitoDataModel extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ZitoLab4DB.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_MOVIES = "movies";
public static final String MOVIE_ID = "id";
public static final String MOVIE_TITLE = "title";
public static final String MOVIE_GENRE = "genre";
public static final String MOVIE_YEAR = "releaseYear";
public ZitoDataModel(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_MOVIES + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," +
MOVIE_TITLE + " TEXT," + MOVIE_GENRE + " STRING, " + MOVIE_YEAR + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
}
public void addMovie(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(MOVIE_TITLE, title);
values.put(MOVIE_GENRE, genre);
values.put(MOVIE_YEAR, year);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_MOVIES, null, values);
db.close();
}
public Cursor readEntry(){
SQLiteDatabase db = this.getWritableDatabase();
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dbCursor = db.query(ZitoDataModel.TABLE_MOVIES, allColumns,
null, null, null, null, null);
if (dbCursor !=null) {
dbCursor.moveToFirst();
}
return dbCursor;
}
}
DataController.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ZitoDataController {
private ZitoDataModel dataModel;
private Context movieContext;
private SQLiteDatabase database;
public ZitoDataController(Context context) {
movieContext = context;
}
public ZitoDataController open() throws SQLException {
dataModel = new ZitoDataModel(movieContext);
database = dataModel.getWritableDatabase();
return this;
}
public void close()
{
dataModel.close();
}
public void insertData(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(ZitoDataModel.MOVIE_TITLE, title);
values.put(ZitoDataModel.MOVIE_GENRE, genre);
values.put(ZitoDataModel.MOVIE_YEAR, year);
database.insert(ZitoDataModel.TABLE_MOVIES, null, values);
}
public Cursor readEntry() {
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dataCursor = database.query(ZitoDataModel.TABLE_MOVIES,
allColumns, null, null, null, null, null);
if (dataCursor != null) {
dataCursor.moveToFirst();
}
return dataCursor;
}
}
You possibly modified the table in a later moment (after the very first run).
Uninstall and reinstall your app.
Or, alternatively, increase the value of this constant: DATABASE_VERSION
In the first case, the database will be created normally (for the first time).
The second case causes the onUpgrade() method to fire which will in turn call
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
So, de facto, deleting the existing table and then re-creating it.

how to update integer value in sqlite android

i am having problem with the updation part of the below code. insertion is working properly. when i added the update method for addition/subtraction of the integer stored in the database, the code is no longer working. it says the app has closed unfortunately. the app is not even opening. please check the update method and make sufficient changes.
first i used this code to accept name and email. then this code was changed to accept a number and email. variable name and column name has not been changed. please dont get confused with these.
thank you.
MainActivity.java
package com.sqltut;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save,load,updatebtn;
EditText name,email,update;
DataHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save=(Button) findViewById(R.id.save);
load=(Button) findViewById(R.id.load);
name=(EditText) findViewById(R.id.name);
email=(EditText) findViewById(R.id.email);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName=name.getText().toString();
String getEmail=email.getText().toString();
int number = Integer.parseInt(getName);
handler=new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(number, getEmail);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getEmail;
Integer getName;
getName=0;
getEmail="";
handler=new DataHandler(getBaseContext());
handler.open();
Cursor C=handler.returnData();
if(C.moveToFirst())
{
do
{
getName=C.getInt(0);
getEmail=C.getString(1);
}while(C.moveToNext());
}
handler.close();
Toast.makeText(getBaseContext(), "Name:"+getName+" And Email:"+getEmail,Toast.LENGTH_LONG).show();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int number,flag=0; //flag to check for addition or subtraction
String getupdate=update.getText().toString();
number=Integer.parseInt(getupdate);
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(number,flag);
//subtraction: flag=0, addition: flag=1
handler.close();
}
});
//to call next activity
/* Button createAppointment = (Button)findViewById(R.id.Next);
createAppointment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, Page2.class);
MainActivity.this.startActivity(myIntent);
}
});
*/ }
#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;
}
}
DataHandler.java
package com.sqltut;
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 DataHandler {
public static final String NAME="name";
public static final String EMAIL="email";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(name text not null, email 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) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS mytable ");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(Integer name, String email)
{
ContentValues content=new ContentValues();
content.put(NAME, name);
content.put(EMAIL,email);
return db.insert(TABLE_NAME, null, content);
}
public void updateData(Integer number,Integer flag)
{
db = dbhelper.getReadableDatabase();
String select = "select name from " + TABLE_NAME ;
Cursor c = db.rawQuery(select, null);
int current=0;
if (c.moveToFirst()) {
current= Integer.parseInt(c.getString(0));
}
if(flag==0)//subtraction
{
current=current-number;
}
else//addition
{
current=current+number;
}
c.close();
db.close();
db = dbhelper.getReadableDatabase();
ContentValues content=new ContentValues();
content.put(NAME, current);
db.update(TABLE_NAME, content,null,null);
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[] {NAME,EMAIL}, null, null, null, null, null);
}
}
Edited updateData()
public void updateData(Integer value,Integer flag)
{
db = dbhelper.getReadableDatabase();
String selectQuery = "select balance from " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
int current = 0;
if (cursor.moveToFirst()) {
current= Integer.parseInt(cursor.getString(0));
}
if(flag==0){
current = current-value;
}else {
current = current+value ;
}
cursor.close();
db.close();
try{
db = dbhelper.getWritableDatabase();
String rawQuery = "update mytable set balance="+current;
db.rawQuery(rawQuery, null);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Code worked. db.rawQuery(rawQuery, null); changed to db.execSQL(rawQuery);
You can update any value in your table by below method:
public void updateInteger(Integer newID)
{
try{
sqliteDb = appDb.getWritableDatabase();
String rawQuery = "update <table_name> set id="+newID;
sqliteDb.rawQuery(rawQuery, null);
Log.v(TAG, "ID updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

Can't instantiate Class and no empty constructor error

I am making an application and I have made a class setup email.java in which I am saving the values entered by the user in sqlite database.But the class is not able to load and it is saying that:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.astrada/com.example.astrada.Setupemail}:
java.lang.InstantiationException: can't instantiate class com.example.astrada.Setupemail; no empty constructor
Here is my code:
package com.example.astrada;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.astrada.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Setupemail extends Activity implements OnClickListener {
EditText editEmail, editPhon1, editPhon2, editphone3, editphone4, uname,
useraddress;
TextView TitleInfo;
Button save;
SqlOpenHelper mHelper;
Cursor mCursor;
SimpleCursorAdapter mAdapter;
private final Context context;
private SqlOpenHelper DBHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "databaseofuser.db";
private static final String DATABASE_TABLE = "usertable";
private static final int DATABASE_VERSION = 1;
public static final String EMAIL_COLUMN = "email";
public static final String PHONE1_COLUMN = "phon1";
public static final String PHONE2_COLUMN = "phon2";
public static final String PHONE3_COLUMN = "phon3";
public static final String PHONE4_COLUMN = "phon4";
public static final String UNAME_COLUMN = "phon4";
public static final String UADDR_COLUMN = "phon4";
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + EMAIL_COLUMN + "," + PHONE1_COLUMN + ","
+ PHONE2_COLUMN + "," + PHONE3_COLUMN + "," + PHONE4_COLUMN + ","
+ UNAME_COLUMN + "," + UADDR_COLUMN + ");";
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setupemail);
editEmail = (EditText) this.findViewById(R.id.editEmail);
editPhon1 = (EditText) this.findViewById(R.id.editPhon1);
editPhon2 = (EditText) this.findViewById(R.id.editPhon2);
editphone3 = (EditText) this.findViewById(R.id.editPhon3);
editphone4 = (EditText) this.findViewById(R.id.editPhon3);
uname = (EditText) this.findViewById(R.id.nameofuser);
useraddress = (EditText) this.findViewById(R.id.addressofuser);
editPhon1.append("+91");
editPhon2.append("+91");
editphone3.append("+91");
editphone4.append("+91");
mHelper = new SqlOpenHelper(this);
save = (Button) this.findViewById(R.id.btnSaveData);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String email, phon1, phon2, phon3, phon4;
boolean isEntryValid, isPhon1Valid, isPhone2Valid;
if (v == save) {
email = editEmail.getText().toString();
phon1 = editPhon1.getText().toString();
phon2 = editPhon2.getText().toString();
phon3 = editphone3.getText().toString();
phon4 = editphone4.getText().toString();
if (isEmailIdValid(email) && isPhoneValid(phon1)
&& isPhoneValid(phon2)) {
if (phon1.equals(phon2) || phon1.equals(phon3)
|| phon1.equals(phon4) || phon2.equals(phon3)
|| phon2.equals(phon4) || phon3.equals(phon4)) {
Toast.makeText(getApplicationContext(),
" Can't enter same numbers!!", Toast.LENGTH_LONG)
.show();
} else {
// /Saveinto DB
ContentValues cv = new ContentValues();
cv.put(EMAIL_COLUMN, editEmail.getText().toString());
cv.put(PHONE1_COLUMN, editPhon1.getText().toString());
cv.put(PHONE2_COLUMN, editPhon2.getText().toString());
cv.put(PHONE3_COLUMN, editphone3.getText().toString());
cv.put(UNAME_COLUMN, uname.getText().toString());
cv.put(UADDR_COLUMN, useraddress.getText().toString());
mDb.insert(DATABASE_TABLE, null, cv);
mCursor.requery();
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Good Job!!",
Toast.LENGTH_LONG).show();
}
} else {
String x = "Invalid Entry!!\nProvide Information Properly..";
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG)
.show();
editEmail.setText("");
}
}
// TODO Auto-generated method stub
}
private boolean isPhoneValid(String phon) {
final Pattern pattern = Pattern.compile(
"^([\\+](91))?([7-9]{1})([0-9]{9})$", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE);
Matcher match = pattern.matcher(phon);
if (match.matches()) {
return true;
} else {
return false;
}
}
private boolean isEmailIdValid(String Email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = Email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public class SqlOpenHelper extends SQLiteOpenHelper {
public SqlOpenHelper() {
super(context, null, null, 0);
}
public SqlOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, null);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
public SQLiteOpenHelper open() throws SQLException {
mDb = DBHelper.getWritableDatabase();
return this;
}
public void colse() {
DBHelper.close();
}
public long insertContact(String email, String phon1, String phon2,
String phon3, String phon4, String name, String address) {
ContentValues initialValues = new ContentValues();
initialValues.put(EMAIL_COLUMN, email);
initialValues.put(PHONE1_COLUMN, phon1);
initialValues.put(PHONE2_COLUMN, phon2);
initialValues.put(PHONE3_COLUMN, phon3);
initialValues.put(PHONE4_COLUMN, phon4);
initialValues.put(UNAME_COLUMN, name);
initialValues.put(UADDR_COLUMN, address);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version" + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new
// version. Multiple previous versions can be handled by
// comparing oldVersion and newVersion values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(db);
}
}
}
Activity should not have constructor! All should be done in lifecycle callbacks. Move content from ctor to onCreate() and remove ctor:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
Drop this:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
and delete context field. Setupemail class is inherited from Activity, it's a subclass of Context itself. If you want to reference Context you can use getBaseContext in inner class or even omit it at the Setupemail class.
you don't have an empty constructor. It needs to be defined when you define the other constructors
public Setupmail()
{
}

Data not inserted into SQLite database on android?

I have developed an Android database application.
The problem is that when I click the add button then a message shows that data was successfully added.
But the data is not inserted into the database.
I then open the database with SQLite viewer and there I can't find any of the data I inserted...
Register page code :
package com.example.dbapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Register extends Activity {
Button add;
TextView b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
add = (Button) findViewById(R.id.btnReg);
b = (TextView) findViewById(R.id.etName);
c = (TextView) findViewById(R.id.etOccu);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String name = b.getText().toString();
String occ = c.getText().toString();
DataCon entry = new DataCon(Register.this);
entry.open();
entry.createEntry(name, occ);
entry.close();
Toast toast = Toast.makeText(getApplicationContext(), "Sucess", Toast.LENGTH_SHORT);
toast.show();
}
catch(Exception e) {
String err = e.toString();
Toast toast = Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
Database Connection code :
package com.example.dbapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataCon {
public static final String rowid = "_id";
public static final String name = "persons_name";
public static final String hot = "persons_hotness";
private static final String DB_NAME = "myDB";
private static final String DB_TABLE = "tbl_me";
private static final int DB_VER = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + "TEXT NOT NULL, " +
hot + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " +DB_TABLE);
onCreate(db);
}
}
public DataCon(Context c) {
ourContext = c;
}
public DataCon open() {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name2, String occ) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(name, name2);
cv.put(hot, occ);
return ourDatabase.insert(DB_TABLE, null, cv);
}
}
Now how can I solve the problem? thanks
An error in your sql. You haven't provide space between column name and type. Correct one should be
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + " TEXT NOT NULL, " +
--------------------------- ^
hot + " TEXT NOT NULL);");`

Categories

Resources