EditText Always Return Null - Java NullPointerException - java

Good day I'm having a problem with EditText. I was following a tutorial about SQLite - tutorial. It's like my EditText don't detect any value. I even try to check them if they're empty. Here's my sample code:
AddItemsActivity.java
public class AddItemsActivity extends AppCompatActivity implements View.OnClickListener{
SQLiteLocalDatabase sqLiteLocalDatabase;
EditText editTextFullName;
EditText editTextAddress;
EditText editTextEmailAdd;
EditText editTextPassword;
EditText editTextIDNO;
Button btnSave;
Button btnUpdate;
Button btnSearch;
Button btnDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_items);
sqLiteLocalDatabase = new SQLiteLocalDatabase(AddItemsActivity.this);
//CALL FUNCTION
setUpWidgets();
}
public void setUpWidgets(){
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
editTextAddress = (EditText) findViewById(R.id.Location);
editTextEmailAdd = (EditText) findViewById(R.id.editTextEmailAddress);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextIDNO = (EditText) findViewById(R.id.editTextID);
btnSave = (Button) findViewById(R.id.buttonAddContacts);
btnSave.setOnClickListener(this);
btnUpdate = (Button) findViewById(R.id.buttonUpdate);
btnUpdate.setOnClickListener(this);
btnSearch = (Button) findViewById(R.id.buttonSearch);
btnSearch.setOnClickListener(this);
btnDelete = (Button) findViewById(R.id.buttonDelete);
btnDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = Integer.parseInt(editTextIDNO.getText().toString().trim());
String fullName = editTextFullName.getText().toString().trim();
String location = editTextAddress.getText().toString().trim();
String emailAdd = editTextEmailAdd.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
switch (v.getId()){
case R.id.buttonAddContacts:
//IF result == -1
long result = sqLiteLocalDatabase.insert(id,fullName,location,emailAdd,password);
if(result == -1){
Toast.makeText(AddItemsActivity.this, "Error",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(AddItemsActivity.this, "Sucess Id:"+result,Toast.LENGTH_LONG).show();
}
break;
case R.id.buttonUpdate:
long update = sqLiteLocalDatabase.update(Integer.parseInt(getValue(editTextIDNO)),
getValue(editTextFullName),
getValue(editTextAddress),
getValue(editTextEmailAdd),
getValue(editTextPassword)
);
if(update == 0){
Toast.makeText(AddItemsActivity.this, "Error Updating",Toast.LENGTH_LONG).show();
}else
if(update == -1){
Toast.makeText(AddItemsActivity.this, "Updating",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(AddItemsActivity.this, "Error All data updated Id:"+update,Toast.LENGTH_LONG).show();
}
break;
case R.id.buttonSearch:
break;
case R.id.buttonDelete:
long delete = sqLiteLocalDatabase.delete(Integer.parseInt(getValue(editTextIDNO)));
if(delete == 0) {
Toast.makeText(AddItemsActivity.this, "Error Delete", Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(AddItemsActivity.this, "Success Delete", Toast.LENGTH_LONG).show();
}
break;
}
}
public String getValue(EditText editText){
return editText.getText().toString().trim();
}
#Override
protected void onStart() {
super.onStart();
sqLiteLocalDatabase.setUpDb();
}
#Override
protected void onStop() {
super.onStop();
sqLiteLocalDatabase.closeTransactionDb();
}
}
And for database: SQLiteLocalDatabase .java
public class SQLiteLocalDatabase extends SQLiteOpenHelper{
private SQLiteDatabase sqLiteDatabase;
private static final String DB_NAME = "project.db";
private static final int VERSION = 1;
public static final String DB_TABLE = " user ";
public static final String ID = " _id ";
public static final String FULL_NAME = " fullname ";
public static final String LOCATION = " location ";
public static final String EMAIL_ADD = " email ";
public static final String PASSWORD = " password ";
public SQLiteLocalDatabase(Context context) {
super(context, DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String queryTable = " CREATE TABLE " + DB_TABLE + "( " + ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+ FULL_NAME + " TEXT NOT NULL, " + LOCATION + " TEXT NOT NULL, " + EMAIL_ADD + " TEXT NOT NULL, " + PASSWORD + " TEXT NOT NULL" + " ) ";
db.execSQL(queryTable);
}
public void setUpDb(){
//TO OPEN DATABASE - RE-WRITABLE
sqLiteDatabase = getWritableDatabase();
}
public void closeTransactionDb(){
//CLOSE DB IF OPEN
if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
sqLiteDatabase.close();
}
}
//INSERT DATA
public long insert(int id,String fullname, String location,String email,String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
if(id != -1) {
values.put(ID,id);
values.put(FULL_NAME, fullname);
values.put(LOCATION, location);
values.put(EMAIL_ADD, email);
values.put(PASSWORD, password);
}
//Object Table, column, values
return sqLiteDatabase.insert(DB_NAME, null, values);
}
//UPDATE
public long update(int id, String fullname,String location,String email, String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
values.put(FULL_NAME,fullname);
values.put(LOCATION,location);
values.put(EMAIL_ADD,email);
values.put(PASSWORD,password);
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.update(DB_NAME, values, where, null);
}
//DELETE
//
public long delete(int id){
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.delete(DB_NAME, where, null);
}
public Cursor getAllRecords(){
String queryDB = "SELECT * FROM " + DB_TABLE;
return sqLiteDatabase.rawQuery(queryDB,null);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Logcat:
addItems.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#color/bg"
tools:context="project.app.elective.ccs.mobileappproject.activities.AddItemsActivity">
<include android:id="#+id/toolbar_extend"
layout="#layout/toolbar"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Full Name"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:textColorHint="#color/textPrimaryColor"
android:id="#+id/textViewFullName"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_below="#+id/toolbar_extend"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Location Address"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:textColorHint="#color/textPrimaryColor"
android:id="#+id/editTextLocation"
android:layout_below="#+id/textViewFullName"
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/textPrimaryColor"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:inputType="text"
android:hint="Email Address"
android:id="#+id/editTextEmailAddress"
android:layout_below="#+id/editTextLocation"
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:textColorHint="#color/textPrimaryColor"
android:hint="Password"
android:inputType="textPassword"
android:id="#+id/editTextPassword"
android:layout_below="#+id/editTextEmailAddress"
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/activity_vertical_margin"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:textColor="#color/textPrimaryColor"
android:id="#+id/buttonAddContacts"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
style="?attr/borderlessButtonStyle"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:textColor="#color/textPrimaryColor"
android:id="#+id/buttonUpdate"
android:layout_below="#+id/buttonAddContacts"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
style="?attr/borderlessButtonStyle"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:textColor="#color/textPrimaryColor"
android:id="#+id/buttonSearch"
android:layout_below="#+id/buttonDelete"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
style="?attr/borderlessButtonStyle"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:textColor="#color/textPrimaryColor"
android:id="#+id/buttonDelete"
android:layout_below="#+id/buttonUpdate"
style="?attr/borderlessButtonStyle"/>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_icon"
android:hint="ID no, you can leave it!"
android:inputType="text"
android:textColorHint="#color/textPrimaryColor"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextPassword"
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>

You can't give id "Location" to an editText.
editTextAddress = (EditText) findViewById(R.id.Location);
change it to something else like "location" if you want.
Edit
editTextFullName = (EditText) findViewById(R.id.textViewFullName);
editTextAddress = (EditText) findViewById(R.id.editTextLocation);

Like others said
You are giving wrong id of your textview, you need to change your xml editext id from editTextFullName to textViewFullName
or Change this statement
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
with
editTextFullName = (EditText) findViewById(R.id.textViewFullName);
and just as a heads up in your "insert()" function in SQLiteLocalDatabase you might want to change
return sqLiteDatabase.insert(DB_NAME, null, values);
to
return sqLiteDatabase.insert(DB_TABLE, null, values);
because you might end up with a android.database.sqlite.SQLiteException: no such table: project.db

logcat showing NullPointerException at fullName string setting statement in below method (i.e onclick), so make sure editTextFullName textview is not null (having some value) before apply toString() and trim() methods on it.
I'm suspecting select query not return all fields values properly. please try your query separately using some sqlite client tool to check actual result of your select query.
public void onClick(View v) {
int id = Integer.parseInt(editTextIDNO.getText().toString().trim());
*****String fullName = editTextFullName.getText().toString().trim();*****
String location = editTextAddress.getText().toString().trim();
String emailAdd = editTextEmailAdd.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();

Problem : It's like my EditText don't detect any value.
You are giving wrong id dear.. you need to change your java editext id from editTextFullName to textViewFullName
Change this statement
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
with
editTextFullName = (EditText) findViewById(R.id.textViewFullName);

NullPointerException is because your EditText full name is null means can not find
I have figure out that your code for EditText for id is "textViewFullName" and you are getting id "editTextFullName"
just either you change the
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
to
editTextFullName = (EditText) findViewById(R.id.textViewFullName);
-------------OR----------------------
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Full Name"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:textColorHint="#color/textPrimaryColor"
android:id="#+id/textViewFullName"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_below="#+id/toolbar_extend"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
to
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Full Name"
android:drawableLeft="#drawable/ic_action_icon"
android:drawableStart="#drawable/ic_action_icon"
android:textColorHint="#color/textPrimaryColor"
android:id="#+id/editTextFullName"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_below="#+id/toolbar_extend"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"/>
Hope this helps. If if solve your problem kindly accept it. Thank you.

Change editTextFullName = (EditText) findViewById(R.id.editTextFullName); to editTextFullName = (EditText) findViewById(R.id.textViewFullName);. You are referring to wrong ID, that's why it always null.
Add
sqLiteDatabase=this.getWritableDatabase();
ContentValues values=new ContentValues();
inside your insert method

Related

Dispaying slitedata in edittext and textview in profileactivity and updating the data in profile

I have a login activity, registration activity, and profile activity. After I press the profile activity i want it to display user data in the profile.
I am trying to display data of sqlite database in profile activity in text view and edit text and update the data in the profile activity. Here is the code.
Here is my user profile xml.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UserProfile">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#fece2f"
android:padding="20dp">
<ImageView
android:id="#+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerVertical="true"
android:src="#drawable/profile_image" />
<TextView
android:id="#+id/Username_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/profile_image"
android:fontFamily="#font/alfa_slab_one"
android:includeFontPadding="false"
android:text="Ian Kipchumba"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/username_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Username_profile"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/profile_image"
android:includeFontPadding="false"
android:text="ian kipchumba"
android:textSize="14sp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/full_name_profile"
android:hint="User Name"
android:drawableLeft="#drawable/profile_icon"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/admission_profile"
android:hint="Admission"
android:drawableLeft="#drawable/ic_adm"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/password_profile"
android:hint="Password"
android:drawableLeft="#drawable/ic_lock"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<Button
android:id="#+id/button_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fece2f"
android:fontFamily="#font/alfa_slab_one"
android:text="UPDATE"
android:onClick="run"/>
</LinearLayout>
</LinearLayout>
Here is my USERPROFILE.class
public class UserProfile extends AppCompatActivity {
DatabaseHelper db;
EditText name, admission, password;
TextView Username_profile, username_field;
Button btnviewUpdate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
db = new DatabaseHelper(this);
//Hooks
name = (EditText) findViewById(R.id.full_name_profile);
admission = (EditText) findViewById(R.id.admission_profile);
password = (EditText) findViewById(R.id.password_profile);
Username_profile = (TextView) findViewById(R.id.Username_profile);
username_field = (TextView) findViewById(R.id.username_field);
btnviewUpdate = (Button) findViewById(R.id.button_update);
}
}
Here is my DATABASEHELPER.class
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME ="register.db";
public static final String TABLE_NAME ="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="admission";
public static final String COL_4 ="password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,admission TEXT, password TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public long addUser(String username, String admission, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("admission",admission);
contentValues.put("password",password);
long res = db.insert("registeruser",null,contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password){
String[] columns = { COL_1, COL_3};
SQLiteDatabase db = getReadableDatabase();
String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = { username, password };
Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count>0)
return true;
else
return false;
}
}

How to make working CheckBox inside ListView (which has items from sqlite database)

I'm trying to make working CheckBox inside ListView.
Layout is just main.xml which shows multiple row.xml when new information is added to sqlite database.
I can make working CheckBox in main.xml, but I don't know how to make working CheckBox inside row.xml.
AndroidSQLite.java (shows main.xml, and row.xml inside it)
public class AndroidSQLite extends Activity {
(...)
checkBoxMain = (CheckBox)findViewById(R.id.checkboxmain1);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter._id,
SQLiteAdapter.KEY_NAME,
SQLiteAdapter.KEY_QUANTITY,
SQLiteAdapter.KEY_CHECKED};
int[] to = new int[]{R.id.id, R.id.name, R.id.quantity,
R.id.checkboxmain};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from,
to);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(listContentOnItemClickListener);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
checkBoxMain.setOnClickListener(onCheckboxClicked);
}
CheckBox OnClickListener (AndroidSQLite.java)
CheckBox.OnClickListener onCheckboxClicked
= new CheckBox.OnClickListener() {
public void onClick(View v) {
CheckBox checkBoxMain = (CheckBox)
findViewById(R.id.checkboxmain1);
boolean checked = checkBoxMain.isChecked();
if (checked) {
Boolean data1 = checkBoxMain.isChecked();
mySQLiteAdapter.insertChecked(data1);
updateList();
}
}
};
ListView OnItemClickListener (AndroidSQLite.java)
private ListView.OnItemClickListener listContentOnItemClickListener
= new ListView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position,
long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id =
cursor.getInt(cursor.getColumnIndex(SQLiteAdapter._id));
String item_name =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME));
String item_quantity =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY));
AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidSQLite.this);
// when item in row.xml is clicked alertdialog is shown
// code of AlertDialog
myDialog.show();
}};
onDestroy and updateList() (AndroidSQLite.java)
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/panelup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LIST SQ1"
/>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/panelup"
android:layout_above="#id/paneldown"/>
<CheckBox
android:id="#+id/checkboxmain1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/paneldown"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<EditText
android:id="#+id/quantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
/>
<Spinner
android:id="#+id/mu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/mu_values"
android:layout_weight="2"
/>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="+"
/>
</LinearLayout>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutmain"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:text="M"/>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"
android:text="-" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dip"/>
</LinearLayout>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dip"/>
<CheckBox
android:id="#+id/checkboxmain2"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
(checkboxmain2 from row.xml have android:focusable and android:focusableInTouchMode set on "false" because if it's not false, ListView OnItemClickListener it's notr working)
SQLiteAdapter.java
public class SQLiteAdapter {
(...)
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insertChecked(boolean data1){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CHECKED, data1);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public Cursor queueAll(){
String[] columns = new String[]{_id, KEY_NAME, KEY_PRICE,
KEY_QUANTITY, KEY_MU,
KEY_PDATE, KEY_SHOP, KEY_CHECKED};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
screen
CheckBox on top, which is checked on screen is working CheckBox (checkboxmain1) which adds "1" to database
Is there any way to make response of CheckBoxes in ListView?
The following is a relatively simple way of handling click events of views within an Item of a ListView.
To simply obtain the actual item that has been clicked to distinguish it from another Item you need a Custom Adapter, in this case a Custom Cursor Adapter, in which you can set the view's tag to an appropriate value (the id).
In conjunction with this you use the onClick attribute to specify the method to be called when the view (checkbox) is clicked, which is defined in the Activity.
The following is a working example based upon your code. It uses a simpler and more flexible method for managing the ListView i.e. manageListView
Note some of your code has been omitted (commented out) for convenience.
The Code
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutmain"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:text="M"/>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"
android:text="-" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dip"/>
</LinearLayout>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dip"/>
<CheckBox
android:id="#+id/checkboxmain2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ListViewCheckBoxHanlder"/>
</LinearLayout>
Note the changes made to the CheckBox
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/panelup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LIST SQ1"
/>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/panelup"
android:layout_above="#id/paneldown"/>
<CheckBox
android:id="#+id/checkboxmain1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/paneldown"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<EditText
android:id="#+id/quantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
/>
<Spinner
android:id="#+id/mu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/mu_values"
android:layout_weight="2"
/>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="+"
/>
</LinearLayout>
</RelativeLayout>
AndroidSQLite.java
public class AndroidSQLite extends AppCompatActivity {
CheckBox checkBoxMain;
ListView listContent;
Button buttonAdd;
Cursor cursor;
SQLiteAdapter mySQLiteAdapter;
//SimpleCursorAdapter cursorAdapter; //<<<<<<<<<< NOT USED ANYMORE
MyCursorAdapter myadapter; //<<<<<<<<<< Use a custom adapter that sets the tag of the checkbox to the respective id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBoxMain = (CheckBox)findViewById(R.id.checkboxmain1);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
manageListView(); //<<<<<<<<<< ADDED
/* !!!!!!!!! COMMENTED OUT
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter._id,
SQLiteAdapter.KEY_NAME,
SQLiteAdapter.KEY_QUANTITY,
SQLiteAdapter.KEY_CHECKED};
int[] to = new int[]{R.id.id, R.id.name, R.id.quantity,
R.id.checkboxmain2};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from,
to,0);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(listContentOnItemClickListener);
*/
//buttonAdd.setOnClickListener(buttonAddOnClickListener); //<<<<<<<<<<< you want this back in
}
//<<<<<<<<<< ADDED >>>>>>>>>>
#Override
protected void onResume() {
super.onResume();
manageListView(); //Refresh the List when resuming e.g. returning from another activity
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
cursor.close(); //<<<<<<<<<< SHOULD ALWAYS CLOSE CURSOR
mySQLiteAdapter.close();
}
//<<<<<<<<<< NO LONGER USED >>>>>>>>>>
private void updateList(){
cursor = mySQLiteAdapter.queueAll();
myadapter.swapCursor(cursor);
}
//<<<<<<<< NOTE NOT USED but you'd want this to be used
CheckBox.OnClickListener onCheckboxClicked
= new CheckBox.OnClickListener() {
public void onClick(View v) {
CheckBox checkBoxMain = (CheckBox)
findViewById(R.id.checkboxmain1);
boolean checked = checkBoxMain.isChecked();
if (checked) {
Boolean data1 = checkBoxMain.isChecked();
mySQLiteAdapter.insertChecked(data1);
manageListView(); //<<<<<<<<<< refresh the ListView
}
}
};
//<<<<<<<<<<NOT USED>>>>>>>>>>
private ListView.OnItemClickListener listContentOnItemClickListener
= new ListView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position,
long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id =
cursor.getInt(cursor.getColumnIndex(SQLiteAdapter._id));
String item_name =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME));
String item_quantity =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY));
AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidSQLite.this);
// when item in row.xml is clicked alertdialog is shown
// code of AlertDialog
myDialog.show();
updateList();
}
};
/**<<<<<<<<<< ADDED >>>>>>>>>>>
* Manage the ListView building from new or refreshing the data
*/
private void manageListView() {
cursor = mySQLiteAdapter.queueAll(); // get the source data (cursor) for the listview
if (myadapter == null) {
myadapter = new MyCursorAdapter(this,cursor);
listContent.setAdapter(myadapter);
} else {
myadapter.swapCursor(cursor);
}
}
/**<<<<<<<<<< ADDED >>>>>>>>>>
* Handle the CheckBox being clicked,
* NOTE set in the layout
* #param v The View
*/
public void ListViewCheckBoxHanlder(View v) {
CheckBox cb = v.findViewById(R.id.checkboxmain2);
Toast.makeText(this, "You clicked the CheckBox for ID " + (String) cb.getTag(), Toast.LENGTH_SHORT).show();
int checked = 0;
if (cb.isChecked()) {
checked = 1;
}
long id = Long.valueOf((String) cb.getTag());
mySQLiteAdapter.updateChecked(id,checked);
manageListView();
}
}
Note some code commented out has been replaced, some has been commented out for convenience.
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c) {
super(context, c, true);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
return v;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.row,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//Note Cursor will be positioned appropriately
TextView name = (TextView) view.findViewById(R.id.name);
TextView id = (TextView) view.findViewById(R.id.id);
TextView quantity = (TextView) view.findViewById(R.id.quantity);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkboxmain2);
name.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME)));
id.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter._id)));
quantity.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY)));
cb.setChecked(cursor.getInt(cursor.getColumnIndex(SQLiteAdapter.KEY_CHECKED)) > 0);
cb.setTag(cursor.getString(cursor.getColumnIndex(SQLiteAdapter._id))); //<<<<<<<<<< SET TAG to the ID
}
}
Note the above is a new class.
SQliteAdapter.java
public class SQLiteAdapter {
SQLiteDatabase sqLiteDatabase;
SQLiteHelper sqLiteHelper;
Context context;
public static final String KEY_CHECKED = "checked";
public static final String _id = BaseColumns._ID;
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "quantity";
public static final String KEY_PRICE = "price";
public static final String KEY_MU = "mu";
public static final String KEY_PDATE = "pdate";
public static final String KEY_SHOP = "shop";
public SQLiteAdapter(Context context) {
this.context = context;
openToWrite();
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public long insertChecked(boolean data1) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CHECKED, data1);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int updateChecked(long id,int check) {
ContentValues cv = new ContentValues();
cv.put(KEY_CHECKED,check);
String whereclause = _id + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return sqLiteDatabase.update(MYDATABASE_TABLE,cv,whereclause,whereargs);
}
public Cursor queueAll() {
String[] columns = new String[]{_id, KEY_NAME, KEY_PRICE,
KEY_QUANTITY, KEY_MU,
KEY_PDATE, KEY_SHOP, KEY_CHECKED};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
}
Note this may well be different, it was created to cater for testing.
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String MYDATABASE_NAME = "mydatabase";
public static final int MYDATABASE_VERSION = 1;
public static final String MYDATABASE_TABLE = "mytable";
SQLiteDatabase mDB;
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version) {
super(context, name, factory, version);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_sql = "CREATE TABLE IF NOT EXISTS " + MYDATABASE_TABLE + "(" +
SQLiteAdapter._id + " INTEGER PRIMARY KEY, " +
SQLiteAdapter.KEY_NAME + " TEXT, " +
SQLiteAdapter.KEY_SHOP + " TEXT, " +
SQLiteAdapter.KEY_PDATE + " TEXT, " +
SQLiteAdapter.KEY_PRICE + " REAL, " +
SQLiteAdapter.KEY_QUANTITY + " INTEGER, " +
SQLiteAdapter.KEY_MU + " TEXT, " +
SQLiteAdapter.KEY_CHECKED + " INTEGER DEFAULT 0" +
")";
db.execSQL(crt_tbl_sql);
addSomeTestingData(db,10);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private long addRow(String name, String shop, String pdate, double price, int quantity, String mu, SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(SQLiteAdapter.KEY_NAME,name);
cv.put(SQLiteAdapter.KEY_SHOP,shop);
cv.put(SQLiteAdapter.KEY_PDATE,pdate);
cv.put(SQLiteAdapter.KEY_PRICE,price);
cv.put(SQLiteAdapter.KEY_QUANTITY,quantity);
cv.put(SQLiteAdapter.KEY_MU,mu);
return db.insert(MYDATABASE_TABLE,null,cv);
}
private void addSomeTestingData(SQLiteDatabase db, int number_to_add) {
for (int i = 0; i < number_to_add;i++) {
String suffix = String.valueOf(i);
String day_in_month = suffix;
if (i < 10) {
day_in_month = "0" + day_in_month;
}
addRow(
"Test" + suffix,
"Shop" + suffix,
"2019-01-" + day_in_month,
10.5 + new Double(i * 3),
i * 4,
"mu" + suffix,
db
);
}
}
}
Note this may well be different, it was created to cater for testing.
Result
The following is a screenshot taken after clicking a number of checkboxes so the Toast would be shown :-
And a screenshot after restarting the App (showing that the state has been retained i.e. database updated according to the checkboxes) :-

databasehelper CRUD function

I am a newbie to android studio and have replicated sample code samples to fit my application. The purpose is to read all my company records. I have tried a couple variations without success. The error I get indicates Customers() can not be applied to: with a list of the fields beneath. I have 12 tables with CRUD methods for each. The same error for all tables is the same.
I have all the individual table.java files built and want to finish all the CRUD functions without errors before moving on to the main activity.java file.
// Get All CompanyData =========================================================
public List<CompanyData> GetAllCompanyData() {
List<CompanyData> compdataList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_CompanyData;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
CompanyData compdata;
compdata = new CompanyData();
compdata.setcompanyid(Long.parseLong(cursor.getString(0))); // <==============================================================
compdata.setcompanyname(cursor.getString(1));
compdata.setcompanyaddress1(cursor.getString(2));
compdata.setcompanyaddress2(cursor.getString(3));
compdata.setcompanycity(cursor.getString(4));
compdata.setcompanystate(cursor.getString(5));
compdata.setcompanyzipcode(cursor.getString(6));
compdata.setcompanyphone(cursor.getString(7));
compdata.setcompanyemail(cursor.getString(8));
compdata.setcompanybusinesslicense(cursor.getString(9));
compdata.setcompanytype(cursor.getString(10));
compdataList.add(compdata);
} while (cursor.moveToNext());
}
return compdataList;
}
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Username"
android:textSize="18sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/editName"
android:layout_marginTop="13dp"
android:gravity="center"
android:hint="Enter Password"
android:text="password"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignEnd="#+id/button4"
android:layout_alignRight="#+id/button4"
android:onClick="viewdata"
android:text="view data"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editPass"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_marginTop="23dp"
android:onClick="addUser"
android:text="add user"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button4"
android:layout_alignStart="#+id/button4"
android:layout_below="#+id/editText3"
android:layout_marginTop="13dp"
android:onClick="update"
android:text="Update"
android:textStyle="normal|bold" />
<EditText
android:id="#+id/editText6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/button4"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:ems="10"
android:freezesText="false"
android:hint="Enter Name to Delete Data"
android:inputType="textPersonName" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="41dp"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:onClick="delete"
android:text="delete"
android:textStyle="normal|bold"
tools:ignore="RelativeOverlap" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/button"
android:layout_marginLeft="7dp"
android:layout_marginStart="7dp"
android:layout_marginTop="47dp"
android:ems="10"
android:hint="Current Name"
android:inputType="textPersonName"
android:textSize="14sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/editPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="11dp"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Password"
android:inputType="textPassword"
android:textAllCaps="false"
android:textSize="18sp"
android:textStyle="normal|bold" />
<EditText
android:id="#+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText3"
android:layout_alignStart="#+id/editText3"
android:layout_alignTop="#+id/button3"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="New Name"
android:inputType="textPersonName"
android:textSize="14sp"
android:textStyle="bold|italic" />
</RelativeLayout>'
main activityjava
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText Name, Pass , updateold, updatenew, delete;
DbAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name= (EditText) findViewById(R.id.editName);
Pass= (EditText) findViewById(R.id.editPass);
updateold= (EditText) findViewById(R.id.editText3);
updatenew= (EditText) findViewById(R.id.editText5);
delete = (EditText) findViewById(R.id.editText6);
helper = new DbAdapter(this);
}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Both Name and Password");
}
else
{
long id = helper.insertData(t1,t2);
if(id<=0)
{
Message.message(getApplicationContext(),"Insertion Unsuccessful");
Name.setText("");
Pass.setText("");
} else
{
Message.message(getApplicationContext(),"Insertion Successful");
Name.setText("");
Pass.setText("");
}
}
}
public void viewdata(View view)
{
String data = helper.getData();
Message.message(this,data);
}
public void update( View view)
{
String u1 = updateold.getText().toString();
String u2 = updatenew.getText().toString();
if(u1.isEmpty() || u2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else
{
int a= helper.updateName( u1, u2);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
updateold.setText("");
updatenew.setText("");
} else {
Message.message(getApplicationContext(),"Updated");
updateold.setText("");
updatenew.setText("");
}
}
}
public void delete( View view)
{
String uname = delete.getText().toString();
if(uname.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else{
int a= helper.delete(uname);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
delete.setText("");
}
else
{
Message.message(this, "DELETED");
delete.setText("");
}
}
}
}'
DbAdapterjava
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase"; // Database Name
private static final String TABLE_NAME = "myTable"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
private static final String NAME = "Name"; //Column II
private static final String MyPASSWORD = "Password"; // Column III
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(255) ," + MyPASSWORD + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public long insertData(String name, String pass) {
SQLiteDatabase dbb = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(MyPASSWORD, pass);
long id = dbb.insert(TABLE_NAME, null, contentValues);
return id;
}
public String getData() {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {UID, NAME, MyPASSWORD};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
int cid = cursor.getInt(cursor.getColumnIndex(UID));
String name = cursor.getString(cursor.getColumnIndex(NAME));
String password = cursor.getString(cursor.getColumnIndex(MyPASSWORD));
buffer.append(cid + " " + name + " " + password + " \n");
}
return buffer.toString();
}
public int delete(String uname) {
SQLiteDatabase db = this.getWritableDatabase();
String[] whereArgs = {uname};
int count = db.delete(TABLE_NAME, NAME + " = ?", whereArgs);
return count;
}
public int updateName(String oldName, String newName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, newName);
String[] whereArgs = {oldName};
int count = db.update(TABLE_NAME, contentValues, NAME + " = ?", whereArgs);
return count;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (Exception e) {
Message.message(context, "" + e);
}
}
}'
Messagejava
import android.content.Context;
import android.widget.Toast;
public class Message {
public static void message(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}'

EditText Integer_Input_Type crashes when null

To avoid unnecessary stuff, the validate function is called when the update, delete, insert button are clicked. The problem is with the EditText with inputType="number" i.e with etPrice and etSNumber.I think,there is something wrong with the validate_price() and validate_supplier_no().Please Correct Me.
public class QueryActivity extends AppCompatActivity {
private EditText etName, etPrice, etSupplier, etSNumber;
private Button insert_btn, increment, decrement, update_btn, delete_btn, call_btn;
private TextView quantity_tv;
private int quantity_value = 0;
private TextInputLayout inputLayout_name, inputLayout_price, inputLayout_supplier, inputLayout_supplier_no;
int _id, price, quantity, supplier_no = 0;
String name, supplier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
increment = findViewById(R.id.increment);
decrement = findViewById(R.id.decrement);
insert_btn = findViewById(R.id.insert_btn);
update_btn = findViewById(R.id.update_product);
delete_btn = findViewById(R.id.delete_product);
call_btn = findViewById(R.id.call_btn);
etName = findViewById(R.id.et_name);
etPrice = findViewById(R.id.et_price);
quantity_tv = findViewById(R.id.quantity);
etSupplier = findViewById(R.id.et_supplier);
etSNumber = findViewById(R.id.et_sNumber);
inputLayout_name = findViewById(R.id.textInput_name);
inputLayout_price = findViewById(R.id.textInput_price);
inputLayout_supplier = findViewById(R.id.textInput_supplier);
inputLayout_supplier_no = findViewById(R.id.textInput_supplier_no);
Intent intent = getIntent();
_id = intent.getIntExtra("_id", 0);
name = intent.getStringExtra("name");
price = intent.getIntExtra("price", 0);
quantity = intent.getIntExtra("quantity", 0);
quantity_value = quantity;
supplier = intent.getStringExtra("supplier");
supplier_no = intent.getIntExtra("supplier_no", 0);
String price_str = String.valueOf(price);
if (_id != 0) {
etName.setText(name.toString());
etPrice.setText(String.valueOf(price));
quantity_tv.setText(String.valueOf(quantity).toString());
etSupplier.setText(supplier.toString());
etSNumber.setText(String.valueOf(supplier_no));
insert_btn.setVisibility(View.GONE);
} else {
update_btn.setVisibility(View.GONE);
delete_btn.setVisibility(View.GONE);
}
//OnClickListeners
insert_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
insertProduct();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
updateProduct();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
deleteProduct();
}
});
//add quantity btn
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value += 1;
display(quantity_value);
}
});
//subtract quantity btn
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value -= 1;
if (quantity_value <= -1) {
quantity_value = 0;
}
display(quantity_value);
}
});
call_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(supplier_no==0){
Toast.makeText(getApplicationContext(),"Please Enter Supplier Number",Toast.LENGTH_SHORT).show();
}
else {
Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(supplier_no), null));
startActivity(intent_call);
}
}
});
}//onCreate Ends
public void validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
}
private boolean validate_supplier_no() {
if (TextUtils.isEmpty(etSNumber.getText().toString())) {
inputLayout_supplier_no.setError("Invalid input");
return false;
} else {
inputLayout_supplier_no.setErrorEnabled(false);
return true;
}
}
private boolean validate_supplier() {
if (etSupplier.getText().toString().isEmpty()) {
inputLayout_supplier.setError("Supplier cannot be blanked");
return false;
} else {
inputLayout_supplier.setErrorEnabled(false);
return true;
}
}
private boolean validate_price() {
if (TextUtils.isEmpty(etPrice.getText().toString())) {
inputLayout_price.setError("Invalid input");
return false;
} else {
inputLayout_price.setErrorEnabled(false);
return true;
}
}
private boolean validate_name() {
if (etName.getText().toString().isEmpty()) {
inputLayout_name.setError("Name cannot be blanked");
return false;
} else {
inputLayout_name.setErrorEnabled(false);
return true;
}
}
private void deleteProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
Uri uri = ContentUris.withAppendedId(CONTENT_URI, _id);
int rowsDeleted = getContentResolver().delete(uri, selection, selectionArgs);
}
private void updateProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
int rowsUpdated = getContentResolver().update(uri, values, selection, selectionArgs);
Toast.makeText(this, "Item inserted at: " + rowsUpdated, Toast.LENGTH_SHORT).show();
}
private void insertProduct() {
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
Uri uriRowsInserted = getContentResolver().insert(uri, values);
Toast.makeText(this, "Item inserted at: " + uriRowsInserted, Toast.LENGTH_SHORT).show();
}
//for updating the quantity_tv
public void display(int number) {
quantity_tv.setText(String.valueOf(number));
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e0e0e0"
android:orientation="vertical"
tools:context=".QueryActivity"
>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_price"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Price..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="#+id/increment"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="0"
android:textSize="24sp" />
<Button
android:id="#+id/decrement"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Supplier Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier_no"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_sNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter SupplierNumber..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="#+id/insert_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="ADD IT" />
<Button
android:id="#+id/delete_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="DELETE IT" />
<Button
android:id="#+id/update_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="Save Changes" />
<Button
android:id="#+id/call_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#drawable/button_layout"
android:drawableLeft="#drawable/call"
android:drawablePadding="-40dp"
android:text="CALL" />
</LinearLayout>
</LinearLayout>
Note: With Empty etPrice or etSNumber,this code throws java.lang.NumberFormatException: Invalid int: ""
You should call insertProduct, deleteProduct and updateProduct only if inputs are valid. Change your method validate like below
public boolean validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
return true;
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
return false;
}
and start using as
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(v)) {
deleteProduct();
}
}
});
you can Set Error for your EditText not for your Layout.So you car rewrite your code by this way:
etPrice.setError ("Price cannot be blanked");
return false;
} else {
etPrice.setErrorEnabled(false);
return true;

Android Login Page Not Working Properly

Below provided code is for Login logic, my requirement is after authenticating user, a toast should be displayed, but I am not getting any toast.
I am unable to track reason for this, Any Help would be really very valuable.
Below is my code
MainActivity.class
public class MainActivity extends AppCompatActivity {
private EditText name, username, e_mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doreset(View v) {
EditText name, username, e_mail;
EditText password, re_enter_pass;
name = (EditText) findViewById(R.id.name);
username = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
e_mail = (EditText) findViewById(R.id.e_mail);
name.setText("");
username.setText("");
password.setText("");
e_mail.setText("");
}
public void doSubmit(View view) {
boolean login_validation_result = false;
EditText name, username, e_mail;
EditText password, re_enter_pass;
name = (EditText) findViewById(R.id.name);
username = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
e_mail = (EditText) findViewById(R.id.e_mail);
login_validation(login_validation_result);
if (login_validation_result==true){
Toast respond = new Toast(this);
respond.makeText(this, "Success ful", Toast.LENGTH_SHORT).show();
}
}
private boolean login_validation(boolean validation) {
Toast error = new Toast(this);
EditText name, username, e_mail;
EditText password, re_enter_pass;
name = (EditText) findViewById(R.id.name);
username = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
e_mail = (EditText) findViewById(R.id.e_mail);
if ((name.getText().toString()) == "") {
error.makeText(this, "Please enter your name", Toast.LENGTH_SHORT).show();
return false;
} else if ((name.getText().toString().length()) < 2) {
error.makeText(this, "The name should have more than 2 letters", Toast.LENGTH_SHORT).show();
return false;
} else if ((username.getText().toString()) == "") {
error.makeText(this, "Please enter your username", Toast.LENGTH_SHORT).show();
return false;
} else if ((username.getText().toString().length()) < 4) {
error.makeText(this, "The username should have more than 4 letters", Toast.LENGTH_SHORT).show();
return false;
} else if ((e_mail.getText().toString()) == "") {
error.makeText(this, "Please enter your e-mail", Toast.LENGTH_SHORT).show();
return false;
} else if ((e_mail.getText().toString()).contains("#") == false) {
error.makeText(this, "Please enter a valid e-mail", Toast.LENGTH_SHORT).show();
return false;
} else if ((e_mail.getText().toString()).contains(".com") == false) {
error.makeText(this, "Please enter a valid e-mail", Toast.LENGTH_SHORT).show();
return false;
} else if ((password.getText().toString()) == "") {
error.makeText(this, "Please enter a password", Toast.LENGTH_SHORT).show();
return false;
} else if ((password.getText().toString()).length() < 6) {
error.makeText(this, "Password must contain more than 6 characters", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
}
and here is the xml--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.android.loginpagesample.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please Login To Continue:"
android:textSize="16sp"
android:textStyle="italic" />
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="textPersonName"
android:paddingTop="8dp" />
<EditText
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="textPersonName"
android:paddingTop="8dp"
android:maxLength="10"/>
<EditText
android:id="#+id/e_mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="E-Mail"
android:inputType="textEmailAddress"
android:paddingTop="8dp" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:paddingTop="8dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:textColor="#fff"
android:onClick="doSubmit"/>
<Button
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RESET"
android:textColor="#fff"
android:onClick="doreset"/>
</LinearLayout>
</LinearLayout>
--Thanks!!
Can you try with this
public void doSubmit(View view) {
boolean login_validation_result = false;
EditText name, username, e_mail;
EditText password, re_enter_pass;
name = (EditText) findViewById(R.id.name);
username = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
e_mail = (EditText) findViewById(R.id.e_mail);
login_validation_result = login_validation();
if (login_validation_result==true){
Toast.makeText(this, "Success ful", Toast.LENGTH_SHORT).show();
}
}
and Remove argument in login_validation
private boolean login_validation() {
// your stuff here
}
Explanation
As I comprehend there is passed login_validation_result boolean in login_validation()
method but there is no use of that, There is not assigned value of that,
so it will be as it is and its value will be false every time .so just removed login_validation_result from argument.
and this methods you have implements will return boolean which you want. so just assign that value to the login_validation_result . then it will work
I didn't understand
boolean login_validation(boolean validation){}, .....your method in your code
1.why you are passing a boolean variable in your method though you are not using that parameter in your code.
this method have a boolean return type and you are not using that parameter as well..
Any how I am giving you a solution of your expectation. change your this method your code will work what you was expecting.
public void doSubmit(View view) {
boolean login_validation_result = false;
EditText name, username, e_mail;
EditText password, re_enter_pass;
name = (EditText) findViewById(R.id.name);
username = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
e_mail = (EditText) findViewById(R.id.e_mail);
login_validation_result = login_validation(false/true);
if (login_validation_result==true){
Toast respond = new Toast(this);
respond.makeText(this, "Success ful", Toast.LENGTH_SHORT).show();
}
}

Categories

Resources