Android not displaying data from database - java

I created a very simple application which allows the user to save emergency information into a database and then displays it on a different screen. The information the user can save is first name, blood type, contact number, phone number and relationship type.
However the problem is that the application is not displaying all of the information. It is only displaying the first name. I believe the cursor is not moving onto the next row, so I think the problem is in the code below:
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
Here is the full Code:
Database Class:
package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
/*
* Class for Working with DB
*/
//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION = 1;
//DB Name
private static final String DATABASE_NAME = "details.db";
//Table name
public static final String TABLE_PRODUCTS = "products";
//DB Columns
public static final String COLUMN_ID = "_Id";
public static final String COLUMN_PERSONNAME = "firstName";
public static final String COLUMN_PERSONBLOOD = "bloodType";
public static final String COLUMN_PERSONCONTACT = "contactName";
public static final String COLUMN_PERSONNUMBER = "phoneNumber";
public static final String COLUMN_PERSONRELATION = "relationship";
//Constructor
/*
* Passing information to super class in SQL
* Context is background information
* name of db
* Database version
*/
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
/*
* What to do first time when you create DB
* Creates the table the very first time
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* Remember to use Commas as shown below
*/
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_PERSONNAME + " TEXT, "+
COLUMN_PERSONBLOOD + " TEXT, "+
COLUMN_PERSONCONTACT + " TEXT, "+
COLUMN_PERSONNUMBER + " TEXT, " +
COLUMN_PERSONRELATION + " TEXT " +
");";
//Execute the query
db.execSQL(query);
}
/*
* If ever upgrading DB call this method
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Delete the current table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
//create new table
onCreate(db);
}
//Add new row to the database
public void addProduct(Details details){
//Built in class - set values for different columns
//Makes inserting rows quick and easy
ContentValues values = new ContentValues();
values.put(COLUMN_PERSONNAME, details.get_firstName());
values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
values.put(COLUMN_PERSONCONTACT, details.get_contactName());
values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
values.put(COLUMN_PERSONRELATION, details.get_relationship());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
/*Table was deleted*/
public void deleteProducts(){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PRODUCTS, null, null);
}
//Take DB and Convert to String
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null) {
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
}
Details Class:
package com.example.androidsimpledbapp1;
public class Details {
//primary key
private int _id;
//Properties
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;
//Dont Have to Enter Everything each time
public Details(){
}
public Details(String firstName){
this.set_firstName(firstName);
}
//Passing in details
//Setting values from the user
public Details(String firstName, String bloodType,
String contactName, String phoneNumber,
String relationship){
this.set_firstName(firstName);
this.set_bloodType(bloodType);
this.set_contactName(contactName);
this.set_phoneNumber(phoneNumber);
this.set_relationship(relationship);
}
//Retrieve the data
public int get_id() {
return _id;
}
//Setter allows to give property
public void set_id(int _id) {
this._id = _id;
}
public String get_firstName() {
return _firstName;
}
public void set_firstName(String _firstName) {
this._firstName = _firstName;
}
public String get_bloodType() {
return _bloodType;
}
public void set_bloodType(String _bloodType) {
this._bloodType = _bloodType;
}
public String get_contactName() {
return _contactName;
}
public void set_contactName(String _contactName) {
this._contactName = _contactName;
}
public String get_phoneNumber() {
return _phoneNumber;
}
public void set_phoneNumber(String _phoneNumber) {
this._phoneNumber = _phoneNumber;
}
public String get_relationship() {
return _relationship;
}
public void set_relationship(String _relationship) {
this._relationship = _relationship;
}
}
Edit Screen - The screen where the user adds the data into the DB, upon pressing save the all the database information should display on the main activity
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class EditScreen extends Activity {
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_screen);
//Setting EditTexts
firstNameInput = (EditText) findViewById(R.id.inputname);
bloodTypeInput = (EditText) findViewById(R.id.inputblood);
contacNameInput = (EditText) findViewById(R.id.inputcontact);
phoneNumberInput = (EditText) findViewById(R.id.inputnum);
relationshipInput = (EditText) findViewById(R.id.inputraltion);
//Setting DbHandler object
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void saveMe(View v){
/*
* Making a new object
* Object takes 5 parameters
*/
Details detail = new Details(firstNameInput.getText().toString(),
bloodTypeInput.getText().toString(),
contacNameInput.getText().toString(),
phoneNumberInput.getText().toString(),
relationshipInput.getText().toString());
dbHandler.addProduct(detail);
//Sending Text To Main Activity
String dbString = dbHandler.databaseToString();
Intent myIntent = new Intent(v.getContext(),MainActivity.class);
myIntent.putExtra("mytext",dbString);
startActivity(myIntent);
//End of Sending to Main Activity
//Setting the text in Edit Text
firstNameInput.setText(dbString);
}
public void clearBtnPressed(View v){
dbHandler.deleteProducts();
}
}
MainActivity - This screen displays the data
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Grabs the TextView
mTextView = (TextView)findViewById(R.id.dbname);
mTextView.setText(getIntent().getStringExtra("mytext"));
}
//Changing Activity
public void editBtnPressed(View v){
Intent intent = new Intent(MainActivity.this, EditScreen.class);
startActivity(intent);
}
}

Related

Android Studio: how to do an update through user-id without using a global static variable

I am new to programming and to Android Studio.
I am trying to implement a ProfileActivity for a simple chat-project in which the user is able to update some rows in the User table of a SQLite Database through a simple profile-form after signing up and then signing in in the app.
That should appen through the method updateUser() through the query db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[]{ String.valueOf(user.getId()) }); in the DatabaseHelper Class, as you can see here:
/**
* This method to update user record
*
* #param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_CITY, user.getCity());
values.put(COLUMN_USER_AGE, user.getAge());
values.put(COLUMN_USER_SEX, user.getSex());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[]{ String.valueOf(user.getId()) });
db.close();
}
}
Anyway I was getting all the time from the User-model an id = 0 and the update did not work.
Now, after many attempts, I found a (pseudo)solution providing a global public static integer variable "user_id" and accessing it directly in ProfileActivity. The table-update works fine now. Anyway I know that it is a very bad practice against the principles of data encapsulation, as you can see here:
DatabaseHelper.java
package com.example.chat_project.Sql;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.chat_project.Model.User;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
private static final String COLUMN_USER_AGE = "user_age";
private static final String COLUMN_USER_CITY = "user_city";
private static final String COLUMN_USER_SEX = "user_sex";
private User user;
private Cursor userId;
int rv = -1;
public static int user_id;
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT," + COLUMN_USER_AGE +
" INTEGER," + COLUMN_USER_CITY + " TEXT," + COLUMN_USER_SEX + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method to check user exist or not
*
* #param email
* #param password
* #return true/false
*/
#SuppressLint("Range")
public boolean checkLoggedUser (String email, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex("user_id"));
getLoggedUser(rv);
}
//The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to fill user_id with column index
*
* #param i
*/
public int getLoggedUser(int i){
//stores index of columns
user_id = i;
return user_id;
}
/**
* This method to update user record
*
* #param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_CITY, user.getCity());
values.put(COLUMN_USER_AGE, user.getAge());
values.put(COLUMN_USER_SEX, user.getSex());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[] { String.valueOf(user_id) });
db.close();
}
}
ProfileActivity.java
package com.example.chat_project.Activities;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import com.example.chat_project.Model.User;
import com.example.chat_project.R;
import com.example.chat_project.Sql.DatabaseHelper;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PICK_IMAGE = 100;
private final AppCompatActivity activity = ProfileActivity.this;
private ConstraintLayout constraintLayout;
private AppCompatEditText inputName;
private AppCompatEditText inputAge;
private AppCompatEditText inputCity;
private AppCompatEditText inputSex;
private AppCompatImageView profileImage;
private AppCompatButton saveProfile;
private AppCompatButton pickImage;
private DatabaseHelper databaseHelper;
private User user;
private String user_name, user_sex, user_city;
private int user_age;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setTitle("");
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
inputName = (AppCompatEditText) findViewById(R.id.editTextUserName);
inputAge = (AppCompatEditText)findViewById(R.id.editTextUserAge);
inputCity= (AppCompatEditText)findViewById(R.id.editTextCity);
inputSex = (AppCompatEditText)findViewById(R.id.editTextUserSex);
profileImage = (AppCompatImageView)findViewById(R.id.imageViewProfileImage);
saveProfile = (AppCompatButton) findViewById(R.id.buttonSaveProfile);
pickImage = (AppCompatButton) findViewById(R.id.buttonPickImage);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
saveProfile.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
user = new User();
inputName.setText(user.getName());
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonPickImage:
/**
new MaterialDialog.Builder(this)
.title("set your image")
.items(R.array.uploadImages)
.itemsIds(R.array.itemIds)
.itemsCallback((dialog, view, which, text){
switch (which){
case 0:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
break;
case 1:
profileImage.setImageResource(R.drawable.no_profile_pic);
break;
}
})*/
//insertImageToSQLite();
break;
case R.id.buttonSaveProfile:
postDataToSQLite();
break;
}
}
/**
* This method is to post data to SQLite
*/
private void postDataToSQLite() {
user.setName(inputName.getText().toString().trim());
user.setAge(Integer.parseInt(inputAge.getText().toString().trim()));
user.setSex(inputSex.getText().toString().trim());
user.setCity(inputCity.getText().toString().trim());
// here the static variable from DatabaseHelper is retrieved
user.setId(databaseHelper.user_id);
databaseHelper.updateUser(user);
Toast.makeText(this, "Profile successfully saved", Toast.LENGTH_SHORT).show();
}
}
How can I do in order to update the rows in the User-table without declaring a public static variable for the id?
Thank you very much in advance for every hint!

I have an ArrayList coming from SQL Server stored procedure and I want to insert all the data to a SQLite database. Please look at my code below

I was able to get data from SQL Server, but I don't know what to do after, Please help me or any idea how can I insert the data from my ArrayList to SQLite Database and insert it into a Custom ListView.
.................................................................................................
ConnectionHelper.java
package com.example.storedprocedures;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionHelper {
Connection con;
String ip = "***.***.*.***";
String port = "*****";
String classes = "net.sourceforge.jtds.jdbc.Driver";
String database = "CentralizedDB";
String username = "******";
String password = "********";
String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
#SuppressLint("NewApi")
public Connection conclass(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
try{
Class.forName(classes);
connection = DriverManager.getConnection(url, username, password);
}catch(Exception exception){
Log.e("Error:", exception.getMessage());
}
return connection;
}
}
MainActivity.java
package com.example.storedprocedures;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView lblheader;
Button btnviewall,btnview;
ListView lstTaggedList;
EditText edtid;
Connection connect;
ResultSet rs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblheader = (TextView) findViewById(R.id.lblheader);
lstTaggedList = (ListView) findViewById(R.id.lstTaggedList);
btnviewall = (Button) findViewById(R.id.btnviewall);
btnview = (Button) findViewById(R.id.btnview);
edtid = (EditText) findViewById(R.id.edtid);
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.conclass();
btnviewall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList");
final ArrayList list = new ArrayList();
rs = statement.executeQuery();
while (rs.next()) {
list.add(rs.getString("mrCode"));
list.add(rs.getString("docId_branch"));
list.add(rs.getString("brchName"));
list.add(rs.getString("industry_type"));
list.add(rs.getString("specialization_id"));
list.add(rs.getString("uName"));
list.add(rs.getString("class_id"));
list.add(rs.getString("max_visit"));
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, list);
} catch (SQLException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
}
});
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList '"+edtid.getText().toString()+"'");
final ArrayList list = new ArrayList();
rs = statement.executeQuery();
while (rs.next()) {
list.add(rs.getString("mrCode"));
list.add(rs.getString("docId_branch"));
list.add(rs.getString("brchName"));
list.add(rs.getString("industry_type"));
list.add(rs.getString("specialization_id"));
list.add(rs.getString("uName"));
list.add(rs.getString("class_id"));
list.add(rs.getString("max_visit"));
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, list);
} catch (SQLException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
}
});
lstTaggedList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String item = lstTaggedList.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, item + " selected", Toast.LENGTH_LONG).show();
}
});
}
}
With SQLite on android, the typically way to use an SQLite database is to have a class that extends SQLiteOpenHelper.
SQLiteOpenHelper will if the database does not exist call the onCreate method passing an empty SQLiteDatabase to the method (not totally empty as sqlite_master and android_metadata tables will exist, but empty as far as user tables will be concerned). You can then create the tables using the execSQL method for each table (or other components such as indexes, view triggers).
You can also include other methods that cater for CRUD operations to access the data.
Here's a Simple Demo of a database that drives a ListView.
First DatabaseHelper i.e. the class that extends SQLiteOpenHelper :-
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
private static volatile DatabaseHelper INSTANCE; /* singleton instance of DatabaseHelper */
private SQLiteDatabase db;
/* Constructor (not publicly available) */
private DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
/* Get singleton instance of DatabaseHelper */
public static DatabaseHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DatabaseHelper(context);
}
return INSTANCE;
}
public static final String TABLE_NAME = "the_table";
public static final String COLUMN_MRCODE = BaseColumns._ID; /* Cursor Adapter must have _id column */
public static final String COLUMN_DOCID_BRANCH = "docid_branch";
public static final String COLUMN_BRCHNAME = "brchname";
public static final String COLUMN_INDUSTRY_TYPE = "industry_type";
public static final String COLUMN_SPECIALIZATION_ID = "specilization_id";
public static final String COLUMN_UNAME = "uname";
public static final String COLUMN_CLASS_ID = "class_id";
public static final String COLUMN_MAX_VISIT = "max_visit";
private static final String CRTSQL_THE_TABLE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
COLUMN_MRCODE + " INTEGER PRIMARY KEY" +
"," + COLUMN_DOCID_BRANCH + " INTEGER " +
"," + COLUMN_BRCHNAME + " TEXT " +
"," + COLUMN_INDUSTRY_TYPE + " TEXT " +
"," + COLUMN_SPECIALIZATION_ID + " INTEGER " +
"," + COLUMN_UNAME + " TEXT " +
"," + COLUMN_CLASS_ID + " INTEGER " +
"," + COLUMN_MAX_VISIT + " INTEGER " +
")";
private static final String CRTSQL_DOCID_BRANCH_INDEX =
"CREATE INDEX IF NOT EXISTS " + COLUMN_DOCID_BRANCH + "_" + TABLE_NAME + "_idx001 " +
" ON " + TABLE_NAME + "(" +
COLUMN_DOCID_BRANCH +
")";
/* MUST be overridden (not much use if not used) */
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRTSQL_THE_TABLE);
db.execSQL(CRTSQL_DOCID_BRANCH_INDEX);
}
/* MUST be overridden but doesn't necessarily have to do anything*/
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
/* CRUD */
public long insert(Long mrcode, long docid_branch, String brchname, String industry_type, String uname, long class_id, long max_visit ) {
ContentValues cv = new ContentValues();
if (mrcode != null) {
cv.put(COLUMN_MRCODE,mrcode);
}
cv.put(COLUMN_DOCID_BRANCH,docid_branch);
if (brchname != null) {
cv.put(COLUMN_BRCHNAME,brchname);
}
if (industry_type != null) {
cv.put(COLUMN_INDUSTRY_TYPE,industry_type);
}
if (uname != null) {
cv.put(COLUMN_UNAME,uname);
}
cv.put(COLUMN_CLASS_ID,class_id);
cv.put(COLUMN_MAX_VISIT,max_visit);
return db.insert(TABLE_NAME,null,cv);
}
public Cursor getAllTheTableRows() {
return db.query(TABLE_NAME,null,null,null,null,null,null);
}
#SuppressLint("Range")
public long getNumberOfRowsInTheTable() {
long rv=0;
String output_column = "row_count";
Cursor csr = db.query(TABLE_NAME,new String[]{"count(*) AS " + output_column},null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(output_column));
}
csr.close(); /* should always close cursors when done with them */
return rv;
}
}
as can be seen the database will
have 1 table named the_table
have an index on the docid_branch column
all the component names are defined based upon a single hard coded name.
have columns along the lines of what can be seen from your code.
a singleton approach has been used
some basic CRUD methods have been included to allow data to be inserted and extracted.
To demonstrate use of the DatabaseHelper and a means of driving a ListView (via a CursorAdapter) then MainActivity :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
ListView lv;
SimpleCursorAdapter sca;
Cursor csr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = DatabaseHelper.getInstance(this);
lv = this.findViewById(R.id.lv);
if (dbHelper.getNumberOfRowsInTheTable() < 1) {
addSomeTestData();
}
setOrRefreshListView();
}
/*
Whenever the ListView is to be changed (including initially)
this can be called.
*/
private void setOrRefreshListView() {
csr = dbHelper.getAllTheTableRows(); /* gets the latest data from the database */
if (sca == null) {
sca = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr,
new String[]{DatabaseHelper.COLUMN_UNAME,DatabaseHelper.COLUMN_INDUSTRY_TYPE}, /* The column names in the Cursor */
new int[]{android.R.id.text1,android.R.id.text2},0); /* The respective id's in the ListView's layout */
lv.setAdapter(sca);
} else {
sca.swapCursor(csr);
}
}
private void addSomeTestData() {
dbHelper.insert(001L,111,"Branch001","MINING","FRED",1,10);
dbHelper.insert(null,222,"Branch002","HOSPITALITY","MARY",6,1);
dbHelper.insert(null,333,"Branch003","REFINING","JANE",5,5);
}
}
Note that for brevity a predefined/stock layout has been used
Results
When run then :-
Using App Inspection then :-
as can bee seen the specialization_id is NULL this is because the insert method in the DatabaseHelper class omitted consideration of the column.
Again using App Inspection but with a custom query then :-
android_metadata table can be seen to exist (contains the locale and is android specific)
the docid_branch_the_table_idx001 index has been created.
how can I insert the data from my ArrayList to SQLite Database
So with the above you just need to get an Instance of the the DatabaseHelper and then invoke the insert method whilst looping through your ArrayList.
This isn't the best solution as each insert is done in it's own transaction.

why db.insertWithOnConflict return -1 here?

In this activity, we can enter information of a school's test, and add it to others one.
Test.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.ContentValues;
import android.database.Cursor;
/**
* Created by AmirMasoud Fallahi on 11/18/2017.
*/
public class Test {
public static final String KEY_ID = "testID";
public static final String KEY_NAME = "testName";
public static final String KEY_SCHOOL_NAME = "schName";
public static final String KEY_QUESTION_NUM = "quesNum";
public static final String KEY_PARTICIPANT_NUM = "participantNum";
public static final String KEY_QUALITY_MARK = "qualityMark";
public static final String KEY_LESSON_NUM = "lessonNum";
private int testID;
private String testName;
private String schName;
private int quesNum;
private int participantNum;
private float qualityMark = 0;
private int lessonNum;
public int getLessonNum() {
return lessonNum;
}
public void setLessonNum(int lessonNum) {
this.lessonNum = lessonNum;
}
public String getName() {
return testName;
}
public void setName(String name) {
this.testName = name;
}
public String getSchName() {
return schName;
}
public void setSchName(String schName) {
this.schName = schName;
}
public int getQuesNum() {
return quesNum;
}
public void setQuesNum(int quesNum) {
this.quesNum = quesNum;
}
public int getParticipantNum() {
return participantNum;
}
public void setParticipantNum(int participantNum) {
this.participantNum = participantNum;
}
public float getQualityMark() {
return qualityMark;
}
public void setQualityMark(float qualityMark) {
this.qualityMark = qualityMark;
}
public int getId() {
return testID;
}
public void setId(int id) {
this.testID = id;
}
#Override
public String toString() {
return testName;
}
public ContentValues getContentValuesForDb(){
ContentValues values = new ContentValues();
values.put(Test.KEY_ID, testID);
values.put(Test.KEY_NAME, testName);
values.put(Test.KEY_SCHOOL_NAME, schName);
values.put(Test.KEY_QUESTION_NUM, quesNum);
values.put(Test.KEY_LESSON_NUM, lessonNum);
values.put(Test.KEY_QUALITY_MARK, qualityMark);
values.put(Test.KEY_PARTICIPANT_NUM, participantNum);
return values;
}
public static Test cursorToTest(Cursor cursor){
Test test = new Test();
test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
test.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
test.setQuesNum(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUM)));
test.setParticipantNum(cursor.getInt(cursor.getColumnIndex(KEY_PARTICIPANT_NUM)));
test.setSchName(cursor.getString(cursor.getColumnIndex(KEY_SCHOOL_NAME)));
test.setQualityMark(cursor.getInt(cursor.getColumnIndex(KEY_QUALITY_MARK)));
test.setLessonNum(cursor.getInt(cursor.getColumnIndex(KEY_LESSON_NUM)));
return test;
}
}
TestDbHelper.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by AmirMasoud Fallahi on 11/20/2017.
*/
public class TestDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "test-db";
private static final int DB_VERSION = 1;
public static final String TABLE_TESTS = "tb_tests";
private static final String CMD =
"CREATE TABLE IF NOT EXISTS '" + TABLE_TESTS + "' ('" +
Test.KEY_ID + "' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, '" +
Test.KEY_NAME + "' TEXT, '" +
Test.KEY_SCHOOL_NAME + "' TEXT, '" +
Test.KEY_QUESTION_NUM + "' INTEGER, '" +
Test.KEY_LESSON_NUM + "' INTEGER, '" +
Test.KEY_QUALITY_MARK + "' REAL, '" +
Test.KEY_PARTICIPANT_NUM + "' INTEGER " +
")";
private static final String[] allColumns = {Test.KEY_ID, Test.KEY_NAME, Test.KEY_SCHOOL_NAME,
Test.KEY_QUESTION_NUM, Test.KEY_PARTICIPANT_NUM, Test.KEY_QUALITY_MARK, Test.KEY_LESSON_NUM};
public TestDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CMD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTS);
onCreate(db);
}
public void insetItem(Test test) {
// if(getTests(Test.KEY_ID + " = " + test.getId()).isEmpty()) {
SQLiteDatabase db = getWritableDatabase();
long insertId = db.insertWithOnConflict(TABLE_TESTS, null, test.getContentValuesForDb(), SQLiteDatabase.CONFLICT_REPLACE);
if(insertId == -1) {
Log.i("TestDbHelper", "data insertion failed. (item : " + test.toString() + ")");
} else {
Log.i("TestDbHelper", "data inserted with id : " + insertId);
}
if(db.isOpen()) db.close();
// }
}
public List<Test> getTests(String selection){
SQLiteDatabase db = getReadableDatabase();
List<Test> testList = new ArrayList<>();
Cursor cursor = db.query(TABLE_TESTS, allColumns, selection, null, null, null, null);
if(cursor.moveToFirst()){
do{
Test test = Test.cursorToTest(cursor);
testList.add(test);
} while (cursor.moveToNext());
}
cursor.close();
if(db.isOpen()) db.close();
return testList;
}
}
DefineTestActivity.java :
package com.example.amirmasoudfallahi.testcorrector;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DefineTestActivity extends AppCompatActivity {
TestDBHelper dbHelper;
EditText inputTestName, inputSchName, inputPrtNum, inputQuesNum, inputLessNum;
Button subTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define_test);
dbHelper = new TestDBHelper(this);
inputTestName = (EditText) findViewById(R.id.txt_testNameIn);
inputSchName = (EditText) findViewById(R.id.txt_schNameIn);
inputPrtNum = (EditText) findViewById(R.id.txt_prtcpntNumIn);
inputQuesNum = (EditText) findViewById(R.id.txt_testQuesNumIn);
inputLessNum = (EditText) findViewById(R.id.txt_lessNum);
subTest = (Button) findViewById(R.id.btn_createTestSubmit);
subTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Test test = new Test();
test.setName(inputTestName.getText().toString().trim());
test.setSchName(inputSchName.getText().toString().trim());
test.setQuesNum(Integer.parseInt(inputQuesNum.getText().toString().trim()));
test.setParticipantNum(Integer.parseInt(inputPrtNum.getText().toString().trim()));
test.setLessonNum(Integer.parseInt(inputLessNum.getText().toString().trim()));
dbHelper.insetItem(test);
Intent intent = new Intent(DefineTestActivity.this, AnswerKeysActivity.class);
intent.putExtra("lessonNum", test.getLessonNum());
startActivity(intent);
}
});
}
}
Activity Preview:
[]
in this case, I'm entering information of new Test to be added to Tests list.
when I press the button it should add a new Test to test's table in database.
as you see, in this line it should add it:
dbHelper.insetItem(test);
is insert function, in this line:
long insertId = db.insertWithOnConflict(TABLE_TESTS, null, test.getContentValuesForDb(), SQLiteDatabase.CONFLICT_REPLACE);
it should add it and return a non -1 .
but it return -1, it shows our insertion did failed.
there is no errors. And I actually don't know why it get -1 and didn't insert the item in DB.
Can anyone solve this problem???
Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.
When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.
In your case, COLUMN_ID looks like a good candidate for PRIMARY KEY constraint. The second arg nullColumnHack with value COLUMN_ID in your code is not necessary, you can pass it as null.

Why SQLite to ImageView, BitmapFactory.decodeByteArray Returning Null?

I'm developing a contacts app with a photo. I have Store and retrieve data from SQLite and it's working fine on my list view.
The problem is when I click a list item from it's supposed to show an image view and few other details. but the image is not showing on the Activity
List View on Main Activity
In the empty space here should be an image of the contacts
UserDBHelper.java
package com.example.arif.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
public class UserDBHelper extends SQLiteOpenHelper {
String TAG = "DEBUG";
private static final String DATABASE_NAME = "USERINFO.DB";
private static final String TABLE_NAME = "ContactTable";
private static final String TABLE_COL_NAME = "NAME";
private static final String TABLE_COL_MOB = "MOB";
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
private static final String TABLE_COL_ID = "ID";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+TABLE_NAME+"("+TABLE_COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TABLE_COL_NAME+" TEXT, "+TABLE_COL_MOB+" TEXT, "+TABLE_COL_EMAIL+" TEXT, "+TABLE_COL_IMG+" blob)" ;
public UserDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DataBase", "Database created / Opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DataBase", "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public boolean AddInfo(String Name, String Mob , String Email, byte[] img )
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put("NAME", Name);
CV.put("MOB", Mob);
CV.put("EMAIL", Email );
CV.put("NewImage", img);
long result = db.insert(TABLE_NAME, null,CV);
Log.e("DataBase", "Add Info Bug");
if(result == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getInformation()
{
Cursor data;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select * from " + TABLE_NAME;
data = db.rawQuery(query,null);
return data;
}
public String fetch_Name(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_NAME+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_NAME+""));
}
return Str;
}
public String fetch_MOB(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_MOB+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_MOB+""));
}
return Str;
}
public String fetch_Email(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_EMAIL+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_EMAIL+""));
}
return Str;
}
public Bitmap fetch_Img(int i) { /// THIS FUNCTION IS NOT WORKING
byte[] ImgByte;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select "+TABLE_COL_IMG+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
ImgByte = data.getBlob(data.getColumnIndex(TABLE_COL_IMG+""));
Bitmap bitMAP = BitmapFactory.decodeByteArray(ImgByte, 0, ImgByte.length); // Here it's Always Returning Null
if(bitMAP == null)
{
Log.e( TAG, "Bitmap is null :/ ");
}
return bitMAP;
}
return null;
}
}
DetailsViewActivity
package com.example.arif.contacts;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class DetailsOfContacts extends AppCompatActivity {
int Pos;
TextView Name_View, Mob_View, Email_View;
ImageView Image_View;
UserDBHelper userDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_of_contacts);
//---- ---- Intend Bundle ---- ----
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Pos = -1;
if(bundle != null)
{
Pos = bundle.getInt("Position");
}
Toast.makeText(getApplicationContext(), "Position "+ Pos,Toast.LENGTH_SHORT).show();
// ---- ---- Find View ---- ----
Name_View = (TextView) findViewById(R.id.DetName);
Mob_View = (TextView) findViewById(R.id.DetMob);
Email_View = (TextView) findViewById(R.id.DetEmail);
Image_View = (ImageView) findViewById(R.id.DetImg);
/// --- --- DataBase -----
UserDBHelper userDBHelper = new UserDBHelper(getApplicationContext());
Name_View.setText(userDBHelper.fetch_Name(Pos+1)); // Working Fine
Mob_View.setText(userDBHelper.fetch_MOB(Pos+1));// Working Fine
Email_View.setText(userDBHelper.fetch_Email(Pos+1));// Working Fine
Image_View.setImageBitmap(userDBHelper.fetch_Img(Pos+1)); // it's Not showing The image in activity
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id ;
id = item.getItemId();
if(id == R.id.EditButt)
{
Toast.makeText(getApplicationContext(),"Edit Button Clicked", Toast.LENGTH_SHORT).show();
Intent I = new Intent(DetailsOfContacts.this, EditActivity.class);
startActivity(I);
return true;
}
return super.onOptionsItemSelected(item);
}
}
09-18 09:35:56.866 26144-26144/com.example.arif.contacts E/DEBUG: Bitmap is null :/
Column name of image and email are same
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
Change column name of image.

database helper not able to create database [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I am a beginner to android.
I can't insert into database successfully with my database helper?
Here is my helper class code with the methods for inserting and finding a user
package com.example.tilmac.dbsql;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by TILMAC on 28-11-15.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "User.db";
private static final String TABLE_NAME = "users"; //final variables
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
public DatabaseHelper(Context context) //Constructor
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Create table statement is hardcoded,like this:
private static final String TABLE_CREATE = "create table users (name text not null, email text not null, uname text not null, pass text not null)";
I get an error which says column not found while inserting into database
public void insertUser(Contact c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_UNAME, c.getUname());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String findPass(String s){
db = this.getReadableDatabase();
String query = "select uname, pass from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b="not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(s))
{
b=cursor.getString(1);
break;
}
}while(cursor.moveToNext());
}
return b;
}
#Override
public void onCreate(SQLiteDatabase db) { //OnCreate method
db.execSQL(TABLE_CREATE);
this.db = db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //onUpgrade Method
String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
//and here is my main activity
package com.example.tilmac.dbsql;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by TILMAC on 27-11-15.
*/
public class RegisterActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
///Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
}
public void onRBClick(View v){
if(v.getId()==R.id.Rbutton)
{
EditText n = (EditText)findViewById(R.id.RETname);
EditText e = (EditText)findViewById(R.id.RETemail);
EditText u = (EditText)findViewById(R.id.RETuname);
EditText p1 = (EditText)findViewById(R.id.RETpass);
EditText p2 = (EditText)findViewById(R.id.RETrepass);
String name, email, uname, pass, repass;
name = n.getText().toString();
email = e.getText().toString();
uname = u.getText().toString();
pass = p1.getText().toString();
repass = p2.getText().toString();
if(pass.equals(repass))
{
Contact c = new Contact();
c.setName(name);
c.setEmail(email);
c.setUname(uname);
c.setPass(pass);
helper.insertUser(c);
}
else
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Passwords dont match", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
You added that column after a previous run.
Simply uninstall and reinstall your app.

Categories

Resources