SQLite Database issue not inserting data in the database - java

I have a created database using the SQLite database in android. my database in create but when clicking on in the insert button it shows me "Data inserted" but not adding data into the database.
DatabaseHelper.java
package abc.example.sqlitetraining;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "MARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME + "(ID INTEGER
PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNANE TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int
newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME );
onCreate(sqLiteDatabase);
}
public boolean insertData(String name, String surname, String marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, surname);
contentValues.put(COL_4, marks);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
}
MainActivity.java
package abc.example.sqlitetraining;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
Button btn_inser_data;
EditText text_Name, text_Surname, text_Marks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
btn_inser_data = (Button) findViewById(R.id.btn_insert);
text_Name = (EditText) findViewById(R.id.editTextName);
text_Surname = (EditText) findViewById(R.id.editTextSurname);
text_Marks = (EditText) findViewById(R.id.editTextMarks);
btn_inser_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(text_Name.getText().toString(),
text_Surname.getText().toString(),
text_Marks.getText().toString());
if (isInserted = true) {
Toast.makeText(MainActivity.this, "Data inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Data is not inserted",
Toast.LENGTH_LONG).show();
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:padding="30dp"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="20sp"
android:inputType="textPersonName"
android:hint="Name: "/>
<EditText
android:id="#+id/editTextSurname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:ems="10"
android:textSize="20sp"
android:inputType="textPersonName"
android:hint="Surname: " />
<EditText
android:id="#+id/editTextMarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:ems="10"
android:textSize="20sp"
android:inputType="textPersonName"
android:hint="Marks: "/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editTextMarks"
android:id="#+id/btn_insert"
android:text="INSERT"
android:layout_marginTop="30dp"
android:textSize="18sp"
android:textColor="#ffffff"
android:backgroundTint="#color/colorPrimary"/>
</RelativeLayout>
My app running correctly not showing any error message but not inserting the data into the database. when i trying save data it shows me a blank database. what should I do? please help and thanks.

do not initilize boolean inside if, it will always return true if you initilize there
if (isInserted) {
Toast.makeText(MainActivity.this, "Data inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Data is not inserted",
Toast.LENGTH_LONG).show();
}
just use it like this

Use insertOrThrow method to insert the data.It will throw an exception if your db constraints don't allow a specific insertion. You will get to know the error.

Related

Attempt to invoke virtual method 'android.text.Editable com.google.android.material.textfield.TextInputEditText.getText()' on a null object reference

I am trying to create an Android app with a login and register functionality. Whenever I run the app, the login page renders, and when I click on the create account button, it takes me to the register page as it should. After I fill in the blanks and I click on the register button, the app crashes. I used the debugger, and went through the same process, and I noticed an error message saying "java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable com.google.android.material.textfield.TextInputEditText.getText()' on a null object reference". What could be the root of this problem?
Here is my code:
activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Registration">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutFirstName"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="60dp"
android:hint="#string/first_name"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextFirstName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/first_name"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutLastName"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/last_name"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutFirstName">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/last_name"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutEmail"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/email"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutLastName">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/email"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutNewUsername"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/new_username"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutEmail">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextNewUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/username"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutNewPassword"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="#string/new_password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutNewUsername">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextNewPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutConfirmPassword"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutNewPassword">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextConfirmPassword"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/confirm_password"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/newRegistration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="#string/register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutConfirmPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
Registration.java
package com.zybooks.event_tracking;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
public class Registration extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = Registration.this;
// Field variables
TextInputLayout textInputLayoutFirstName, textInputLayoutLastName, textInputLayoutEmail, textInputLayoutUsername, textInputLayoutPassword, textInputLayoutConfirmPassword;
TextInputEditText textInputEditTextFirstName, textInputEditTextLastName, textInputEditTextEmail, textInputEditTextUsername, textInputEditTextPassword, textInputEditTextConfirmPassword;
Button register;
InputValidation inputValidation;
Database database;
UserModel user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUI();
setupListeners();
initObjects();
}
// initialize views
private void setupUI() {
textInputLayoutFirstName = (TextInputLayout) findViewById(R.id.textInputLayoutFirstName);
textInputLayoutLastName = (TextInputLayout) findViewById(R.id.textInputLayoutLastName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutUsername = (TextInputLayout) findViewById(R.id.textInputLayoutUsername);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutConfirmPassword = (TextInputLayout) findViewById(R.id.textInputLayoutConfirmPassword);
register = findViewById(R.id.newRegistration);
}
// initialize listeners
private void setupListeners() {
register.setOnClickListener(this);
}
// initialize objects to be used
private void initObjects() {
inputValidation = new InputValidation(activity);
database = new Database(activity);
user = new UserModel();
}
// listen the click the view
#Override
public void onClick(View v) {
if (v.getId() == R.id.newRegistration) {
postDataToSQLite();
}
}
// validate the input text fields and post data to SQLite
private void postDataToSQLite() {
if (!inputValidation.isInputEditTextFilled(textInputEditTextFirstName, textInputLayoutFirstName, getString(R.string.error_message_name))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextLastName, textInputLayoutLastName, getString(R.string.error_message_name))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextUsername, textInputLayoutUsername, getString(R.string.error_message_username))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))) {
return;
}
if (!inputValidation.isInputEditTextMatches(textInputEditTextPassword, textInputEditTextConfirmPassword,
textInputLayoutConfirmPassword, getString(R.string.error_password_match))) {
return;
}
if (!database.checkUser(textInputEditTextEmail.getText().toString().trim())) {
user.setFirstName(textInputEditTextFirstName.getText().toString().trim());
user.setLastName(textInputEditTextLastName.getText().toString().trim());
user.setEmail(textInputEditTextEmail.getText().toString().trim());
user.setUsername(textInputEditTextUsername.getText().toString().trim());
user.setPassword(textInputEditTextPassword.getText().toString().trim());
database.addUser(user);
Intent g = new Intent(Registration.this, Grid.class);
startActivity(g);
emptyInputEditText();
//we close this activity
this.finish();
} else {
// Toast to show success message that record is wrong
Toast t = Toast.makeText(this, "Wrong email or password!", Toast.LENGTH_SHORT);
t.show();
}
}
// empty all input edit text
private void emptyInputEditText() {
textInputEditTextFirstName.setText(null);
textInputEditTextLastName.setText(null);
textInputEditTextEmail.setText(null);
textInputEditTextUsername.setText(null);
textInputEditTextPassword.setText(null);
textInputEditTextConfirmPassword.setText(null);
}
}
Database.java
package com.zybooks.event_tracking;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "EventManager.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_FIRST_NAME = "user_first_name";
private static final String COLUMN_USER_LAST_NAME = "user_last_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_USERNAME = "user_username";
private static final String COLUMN_USER_PASSWORD = "user_password";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_FIRST_NAME + " TEXT,"
+ COLUMN_USER_LAST_NAME + " TEXT," + COLUMN_USER_EMAIL + " TEXT, " + COLUMN_USER_USERNAME + " TEXT,"
+ COLUMN_USER_PASSWORD + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
// Constructor
public Database (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);
}
// Create user record
public void addUser (UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_FIRST_NAME, user.getFirstName());
values.put(COLUMN_USER_LAST_NAME, user.getLastName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_USERNAME, user.getUsername());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// Inserting Row
db.insert(TABLE_USER, null, values);
db.close();
}
// Fetch all user and return the list of user records
public List<UserModel> getAllUser() {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_FIRST_NAME,
COLUMN_USER_LAST_NAME,
COLUMN_USER_EMAIL,
COLUMN_USER_USERNAME,
COLUMN_USER_PASSWORD
};
// sorting orders
String sortOrder =
COLUMN_USER_FIRST_NAME + " ASC";
List<UserModel> userList = new ArrayList<UserModel>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_first_name,user_last_name,user_email,user_username,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(TABLE_USER, // Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
UserModel user = new UserModel();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_ID))));
user.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_FIRST_NAME)));
user.setLastName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_LAST_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_EMAIL)));
user.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_USERNAME)));
user.setPassword(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_PASSWORD)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
// Update user record
public void updateUser (UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_USERNAME, user.getUsername());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
// Delete user record
public void deleteUser(UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
// Check if user exist or not
public boolean checkUser(String username) {
//array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_USERNAME + " = ?";
// selection argument
String[] selectionArgs = {username};
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public boolean checkUser(String username, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_USERNAME + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {username, password};
// query user table with conditions
Cursor cursor = db.query(TABLE_USER, //Table to query
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
}
Adding this set of code to my Registration.java file solved my problem.
textInputEditTextFirstName = (TextInputEditText) findViewById(R.id.textInputEditTextFirstName);
textInputEditTextLastName = (TextInputEditText) findViewById(R.id.textInputEditTextLastName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextUsername = (TextInputEditText) findViewById(R.id.textInputEditTextNewUsername);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextNewPassword);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);

My register button does not work properly in android studio

I created project regarding user registering and logging connected with database and unfortunately the register button doesn't work properly whenever I tried to press register in order to check my inputs correct or toasted a message to fill the blanks... here is my cod
Register Java class:
package com.example.registration;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
EditText edtUsernameRegister, edtPasswordRegister , edtEmail;
Button btnRegister;
User user;
Helper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED);
edtUsernameRegister = findViewById(R.id.inputUsername);
edtPasswordRegister = findViewById(R.id.inputPassword);
edtEmail = findViewById(R.id.inputEmail);
btnRegister = findViewById(R.id.btnRegister);
helper = new Helper(this);
user = new User();
TextView btn=findViewById(R.id.alreadyHaveAccount);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public void onClick(View v) {
if (v == btnRegister) {
String username = edtUsernameRegister.getText().toString().trim().toLowerCase();
String password = edtPasswordRegister.getText().toString().trim();
String email = edtEmail.getText().toString().trim();
if (!username.isEmpty() || !password.isEmpty() || !email.isEmpty()) {
user.setUsername(username);
user.setemail(email);
user.setPassword(password);
user.setType("customer");
boolean didSucceed = helper.registerUser(user);
if (didSucceed) {
Toast.makeText(this, "Registered successfully", Toast.LENGTH_SHORT).show();
Intent iii = new Intent(this, LoginActivity.class);
startActivity(iii);
} else {
Toast.makeText(this, "Registration failed..", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "insert all fields, please..", Toast.LENGTH_SHORT).show();
}
}
}
}
Register.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity"
android:background="#drawable/bb">
<TextView
android:id="#+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:textColor="#color/colorWhite"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.13" />
<EditText
android:id="#+id/inputUsername"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="32dp"
android:background="#drawable/input_bg"
android:drawableLeft="#drawable/ic_person"
android:drawablePadding="10dp"
android:ems="10"
android:hint="Username"
android:inputType="textPersonName"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:textColor="#color/colorWhite"
android:textColorHint="#color/colorWhite"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/logo" />
<EditText
android:id="#+id/inputEmail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#drawable/input_bg"
android:drawableLeft="#drawable/ic_email"
android:drawablePadding="10dp"
android:ems="10"
android:hint="Email"
android:inputType="textPersonName"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:textColor="#color/colorWhite"
android:textColorHint="#color/colorWhite"
app:layout_constraintEnd_toEndOf="#+id/inputUsername"
app:layout_constraintStart_toStartOf="#+id/inputUsername"
app:layout_constraintTop_toBottomOf="#+id/inputUsername" />
<EditText
android:id="#+id/inputPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#drawable/input_bg"
android:drawableLeft="#drawable/ic_security"
android:drawablePadding="10dp"
android:ems="10"
android:hint="******"
android:inputType="textPassword"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:textColor="#color/colorWhite"
android:textColorHint="#color/colorWhite"
app:layout_constraintEnd_toEndOf="#+id/inputEmail"
app:layout_constraintStart_toStartOf="#+id/inputEmail"
app:layout_constraintTop_toBottomOf="#+id/inputEmail" />
<Button
android:id="#+id/btnRegister"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#drawable/btn_bg"
android:text="Register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/inputPassword"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/inputPassword"
app:layout_constraintTop_toBottomOf="#+id/inputPassword" />
<TextView
android:id="#+id/alreadyHaveAccount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:shadowColor="#color/colorWhite"
android:text="Already Have an Account?"
android:textColor="#color/colorWhite"
app:layout_constraintEnd_toEndOf="#+id/btnRegister"
app:layout_constraintStart_toStartOf="#+id/btnRegister"
app:layout_constraintTop_toBottomOf="#+id/btnRegister" />
</androidx.constraintlayout.widget.ConstraintLayout>
User class:
package com.example.registration;
public class User {
private int u_id;
private String username;
private String email;
private String password;
private String type;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getemail() {
return email;
}
public void setemail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getu_id() {
return u_id;
}
}
Helper Class:
package com.example.registration;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Helper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "onlySoccer" ;
private static final int DATABASE_VERSION = 7;
private static final String CREATE_TABLE_USER = "create table user(" +
"u_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, " +
"username TEXT NOT NULL UNIQUE, password TEXT NOT NULL, type text, email text NOT NULL UNIQUE);" ;
private static final String CREATE_TABLE_MATCHSSCORE = "create table matchsScore(" +
"m_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, " +
"f_name text unique, t_score Ingteger , f_image text, s_name text, s_image text);";
public Helper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_MATCHSSCORE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL( "DROP TABLE IF EXISTS user" );
onCreate(db);
}
public boolean registerUser(User user) {
ContentValues values = new ContentValues();
values.put("username", user.getUsername());
values.put("email", user.getemail());
values.put("password", user.getPassword());
values.put("type", user.getType());
boolean isValid = getWritableDatabase().insert("user", null, values) > 0;
return isValid;
}
public int getUserId(User user){
Cursor cursor = getReadableDatabase()
.rawQuery("select _id from user where username=?",
new String[]{user.getUsername()});
cursor.moveToFirst();
return cursor.getInt(0);
}
public boolean userIsRegistered(User user) {
String table_name = "user";
String[] columns = {"u_id"};
SQLiteDatabase database = getReadableDatabase();
String selection = "username" + " = ?" + " and" + " password" + " = ?";
String[] selectionArgs = {user.getUsername(), user.getPassword()};
Cursor cursor = database.query(table_name,
columns,
selection,
selectionArgs,
null,
null,
null);
return cursor.getCount()>0;
}
public void insertMatchsScore(MatchsScore matchsScore){
ContentValues values = new ContentValues();
values.put("f_name", matchsScore.getF_name());
values.put("s_name", matchsScore.getS_name());
values.put("f_image", matchsScore.getF_image());
values.put("s_image", matchsScore.getS_image());
values.put("t_score", matchsScore.getT_score());
getWritableDatabase().insert("matchScore", null, values);
}
}
instead of
if (v == btnRegister)
try a switch case statement like so
switch (view.getId()){
case R.id.btnRegister:
String username = edtUsernameRegister.getText().toString().trim().toLowerCase();
String password = edtPasswordRegister.getText().toString().trim();
String email = edtEmail.getText().toString().trim();
if (!username.isEmpty() || !password.isEmpty() || !email.isEmpty()) {
user.setUsername(username);
user.setemail(email);
user.setPassword(password);
user.setType("customer");
boolean didSucceed = helper.registerUser(user);
if (didSucceed) {
Toast.makeText(this, "Registered successfully", Toast.LENGTH_SHORT).show();
Intent iii = new Intent(this, LoginActivity.class);
startActivity(iii);
} else {
Toast.makeText(this, "Registration failed..", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "insert all fields, please..", Toast.LENGTH_SHORT).show();
}
break;
}

How to show properly my data in RecyclerView?

This is the updated code for my RececlerView to show data in my SQLite Database but still I cant make the data to show in my recycler view but there is no errors in my app.
The applications only show "No API Data" which is from this part of my code.
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
I will show you the codes.
This is a part of my DatabaseHelper the method on Listing the data in myDatabase for RecyclerView.
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry._ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = Timerecordshelper.BeneficiaryEntry.COL_1 + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'test#gmail.com';
*/
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //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); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public List<TimeinData> getAllTimeinData() {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry.COL_1,
Timerecordshelper.BeneficiaryEntry.COL_2,
Timerecordshelper.BeneficiaryEntry.COL_3,
Timerecordshelper.BeneficiaryEntry.COL_4,
Timerecordshelper.BeneficiaryEntry.COL_5,
};
// sorting orders
String sortOrder =
Timerecordshelper.BeneficiaryEntry.COL_1 + " ASC";
List<TimeinData> TimeList = new ArrayList<TimeinData>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TimeinData Timerecords = new TimeinData();
Timerecords.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_1))));
Timerecords.setIn(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_2)));
Timerecords.setCustomer(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_3)));
Timerecords.setBranch(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_4)));
Timerecords.setMachine(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_5)));
// Adding user record to list
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return TimeList;
}
TimeinRecyclerAdapter.java
package com.example.serviceapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimeinRecyclerAdapter extends
RecyclerView.Adapter<TimeinRecyclerAdapter.BeneficiaryViewHolder> {
private ArrayList<TimeinData> listBeneficiary;
public ImageView overflow;
private Context mContext;
private ArrayList<TimeinData> mFilteredList;
public TimeinRecyclerAdapter(ArrayList<TimeinData> listBeneficiary, Context
mContext) {
this.listBeneficiary = listBeneficiary;
this.mContext = mContext;
this.mFilteredList = listBeneficiary;
}
public class BeneficiaryViewHolder extends RecyclerView.ViewHolder {
public AppCompatTextView textViewName;
public AppCompatTextView textViewEmail;
public AppCompatTextView textViewAddress;
public AppCompatTextView textViewCountry;
public BeneficiaryViewHolder(View view) {
super(view);
textViewName = view.findViewById(R.id.textViewName);
textViewEmail = view.findViewById(R.id.textViewEmail);
textViewAddress = view.findViewById(R.id.textViewAddress);
textViewCountry = view.findViewById(R.id.textViewCountry);
}
}
#Override
public BeneficiaryViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// inflating recycler item view
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_timeinrecycler, parent, false);
return new BeneficiaryViewHolder(itemView);
}
#Override
public void onBindViewHolder(final BeneficiaryViewHolder holder, int
position) {
holder.textViewName.setText(listBeneficiary.get(position).getId());
holder.textViewName.setText(listBeneficiary.get(position).getIn());
holder.textViewEmail.setText(listBeneficiary.get(position).getCustomer());
holder.textViewAddress.setText(listBeneficiary.get(position).getBranch());
holder.textViewCountry.setText(listBeneficiary.get(position).getMachine());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
}
Timerecordshelper.java
package com.example.serviceapplication;
import android.provider.BaseColumns;
public class Timerecordshelper {
public static final class BeneficiaryEntry implements BaseColumns {
public static final String TABLE_NAME_IN = "TABLE_NAME_IN";
public static final String COL_1 = "Job ID";
public static final String COL_2 = "Time In";
public static final String COL_3 = "Customer:";
public static final String COL_4 = "Branch";
public static final String COL_5 = "Machine";
}
}
This codes acts as the gettersetter for my Recycleview to get data in SQLite.
TimeinData.java
package com.example.serviceapplication;
public class TimeinData {
private int id;
private String In;
private String Customer;
private String Branch;
private String Machine;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIn() {
return In;
}
public void setIn(String In) {
this.In = In;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String Customer) {
this.Customer = Customer;
}
public String getBranch() {
return Branch;
}
public void setBranch(String Branch) {
this.Branch = Branch;
}
public String getMachine() {
return Machine;
}
public void setMachine(String Machine) {
this.Machine = Machine;
}
}
TimerecordsListActivity.java
package com.example.serviceapplication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimerecordsListActivty extends AppCompatActivity {
private AppCompatActivity activity = TimerecordsListActivty.this;
Context context = TimerecordsListActivty.this;
private RecyclerView recyclerViewBeneficiary;
private ArrayList<TimeinData> listBeneficiary;
private TimeinRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
SearchView searchBox;
private ArrayList<TimeinData> filteredList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinrec);
initViews();
initObjects();
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("Job ID")) {
//get all needed extras intent
int id = getIntent().getExtras().getInt("ID");
String in = getIntent().getExtras().getString("Time In");
String customer = getIntent().getExtras().getString("Customer");
String branch = getIntent().getExtras().getString("Branch");
String machine = getIntent().getExtras().getString("Machine");
}else{
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is to initialize views
*/
private void initViews() {
recyclerViewBeneficiary = (RecyclerView)
findViewById(R.id.recyclerViewBeneficiary);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new TimeinRecyclerAdapter(listBeneficiary,
this);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
And this is the XML Layouts of my following codes just showing you to understand more about ID i assigned.
Activity_timeinrec.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.serviceapplication.TimerecordsListActivty">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewBeneficiary"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="?actionBarSize"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_timeinrecycler.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
I expect that the apps shows all the data in TABLE_NAME_IN, but on the otherhand as I said it only shows the No "API Data".

Null pointer exception whilst adding to the DB

I'm developing a simple bird-watching log app for one of my classes at college and I seem to not be able to spot what the heck is going wrong, so after spending a few days banging my head against the wall, I suppose it'd make more sense to just ask for someone with a fresh pair of eyes to have a look.
The app is really simple - I have two activities, one with a ListView, that gets populated by the DB (MainActivity) and another, that takes the arguments to create a new entry (AddActivity). Besides these I have a DBHelper (MySQLiteHelper) to handle my DB calls, a simple class to describe how my object should look like (Sighting), a DataSource class (SightingDataSource) to handle facilitate the calls to the helper and a bunch of non-relevant resources (layouts, etc.) The AddActivity blows up with null pointer exceptions whilst calling the addSighting method. It also for whatever reason doesn't like the int typecast of the bCount field, so for testing purposes I've set a static int, just whilst I figure out the exception portion of my problem.
Here's my source:
AddActivity:
package com.vladislavtachev.cscb763;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends ListActivity {
public SightingsDataSource datasource;
private EditText locFld = null;
private EditText bNameFld = null;
private EditText bCountFld = null;
private Button addSightBtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
locFld = (EditText) findViewById(R.id.locFld);
bNameFld = (EditText) findViewById(R.id.bNameFld);
bCountFld = (EditText) findViewById(R.id.bCountFld);
setContentView(R.layout.activity_add);
addSightBtn = (Button) findViewById(R.id.addSightBtn);
addSightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSight(v);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) { return true; }
return super.onOptionsItemSelected(item);
}
public void addSight(View view){
long time = System.currentTimeMillis()/1000L;
datasource.addSighting(locFld.getText().toString(),
time,
bNameFld.getText().toString(),3
// Integer.parseInt(bCountFld.getText().toString())
);
// datasource.addSighting(sighting);
setContentView(R.layout.activity_main);
}
}
SightingDataSource
package com.vladislavtachev.cscb763;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SightingsDataSource {
//DB info
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COL_ID, MySQLiteHelper.COL_LOCATION,
MySQLiteHelper.COL_TIME, MySQLiteHelper.COL_BNAME, MySQLiteHelper.COL_BCOUNT };
public SightingsDataSource(Context context){
dbHelper = new MySQLiteHelper(context);
}
public void open(){
database = dbHelper.getWritableDatabase();
}
public void close(){ dbHelper.close(); }
public void addSighting(String l, long time, String bName, int bCount){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COL_LOCATION, l);
values.put(MySQLiteHelper.COL_TIME, time);
values.put(MySQLiteHelper.COL_BNAME, bName);
values.put(MySQLiteHelper.COL_BCOUNT, bCount);
long insertId = database.insert(MySQLiteHelper.TABLE_SIGHTINGS, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, MySQLiteHelper.COL_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Sighting newSighting = cursorToSighting(cursor);
cursor.close();
}
private Sighting cursorToSighting(Cursor cursor){
Sighting sighting = new Sighting();
sighting.setId(cursor.getLong(0));
sighting.setLocation(cursor.getString(1));
sighting.setTime(cursor.getLong(2));
sighting.setbName(cursor.getString(3));
sighting.setbCount(cursor.getInt(4));
return sighting;
}
public List<Sighting> getAllSightings(){
List<Sighting> sightings = new ArrayList<Sighting>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Sighting sighting = cursorToSighting(cursor);
sightings.add(sighting);
cursor.moveToNext();
}
cursor.close();
return sightings;
}
}
MySQLiteHelper
package com.vladislavtachev.cscb763;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper{
public final static String DB_NAME = "sightings.db";
public final static int DB_VER = 1;
public final static String TABLE_SIGHTINGS = "sightings";
public final static String COL_ID = "_id";
public final static String COL_LOCATION = "_loc";
public final static String COL_TIME = "_time";
public final static String COL_BNAME = "_bname";
public final static String COL_BCOUNT = "_bcount";
private final static String DB_CREATE = "create table if not exists"
+ TABLE_SIGHTINGS + "("
+ COL_ID + " integer primary key autoincrement, "
+ COL_LOCATION + " text not null, "
+ COL_TIME + " integer not null, "
+ COL_BNAME + " text not null, "
+ COL_BCOUNT + " integer not null);";
public MySQLiteHelper(Context context){
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase database){
database.execSQL(DB_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVer, int newVer){
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGHTINGS);
onCreate(database);
}
}
activity_add.xml layout
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.vladislavtachev.cscb763.AddActivity"
style="#android:style/Theme.Material">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblBName"
android:id="#+id/lblBName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bNameFld"
android:layout_below="#+id/lblBName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblBCount"
android:id="#+id/lblBCount"
android:layout_alignBottom="#+id/bCountFld"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/bCountFld"
android:layout_below="#+id/bNameFld"
android:layout_alignRight="#+id/bNameFld"
android:layout_alignEnd="#+id/bNameFld"
android:layout_toEndOf="#+id/lblBCount"
android:layout_toRightOf="#+id/lblBCount" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblLocation"
android:id="#+id/lblLocation"
android:layout_alignBottom="#+id/locFld"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/locFld"
android:layout_below="#+id/bCountFld"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/lblLocation"
android:layout_toRightOf="#+id/lblLocation" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/addSightBtn"
android:id="#+id/addSightBtn"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<ListView
android:layout_width="10px"
android:layout_height="10px"
android:id="#android:id/list"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/locFld"
android:layout_alignEnd="#+id/locFld" />
</RelativeLayout>
Error stack
07-01 18:08:49.131 2384-2384/com.vladislavtachev.cscb763 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.vladislavtachev.cscb763, PID: 2384
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.vladislavtachev.cscb763.SightingsDataSource.addSighting(java.lang.String, long, java.lang.String, int)' on a null object reference
at com.vladislavtachev.cscb763.AddActivity.addSight(AddActivity.java:75)
at com.vladislavtachev.cscb763.AddActivity$1.onClick(AddActivity.java:38)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
All help is appreciated!
Cheers,
V./
datasource is never initialized in AddActivity. You also call setContentView twice. Delete the second one.
you should Always Check to see if the cursor is null.
if(cursor!=null curosr.moeToNext()){}..
and to close it
if (cursor!=null && !cursor.isClosed){cursor.close();}

Please anyone help me connection with main activity and Adapterclass.

Please anyone tell me how to connect MainActivity class with adapterClass, I am not able to connect to my sqllite database. Any help would be greatly appreciated.
Below is my main activity class
public class LoginActivity extends Activity {
EditText nameText,phoneText;
Button registeredButton,newUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
newUser =(Button)findViewById(R.id.new_user);
newUser.setOnClickListener(new View.OnClickListener()
#Override
public void onClick(View v) {
nameText=(EditText)findViewById(R.id.user_text);
phoneText=(EditText)findViewById(R.id.pass_text);
String name= nameText.getText().toString();
String phone=phoneText.getText().toString();
AdapterClass ad1=new AdapterClass(getApplicationContext(),DatabaseDetail.REGISTER);
ad1.Open();
Cursor cursor=ad1.query("SELECT * FROM CUS_REGISTER WHERE CUS_NAME=? AND CUS_PHONE=?",new String[] { name, phone });
Cursor cursor = ad1.fetchRecords(new String[]{}, null);
startManagingCursor(cursor);
cursor.moveToFirst();
if(cursor.getCount() > 0)
{
Toast.makeText(getApplicationContext(), "Sucess", 5000).show();
}else{
}
}
});
}
}
And this my adapter class code
public Cursor query(String args, String[] pColumnValues) {
// TODO Auto-generated method stub
return database.query(DATABASE_TABLE, pColumnValues, args, null, args, args, args);
}
MainActivity Class
package com.example.sqlitedbtestproject;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.app.Activity;
public class MainActivity extends Activity {
AryaDatabaseAdapter help;
EditText name, address, infoFetcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText1);
address = (EditText) findViewById(R.id.editText2);
infoFetcher = (EditText) findViewById(R.id.editText3);
help = new AryaDatabaseAdapter(this);
}
public void addUser(View view)
{
if(help.insertData(name.getText().toString(), address.getText().toString())>0)
{
MessagePopper.message(this, "Successfully Inserted");
}
else
{
MessagePopper.message(this, "Un successfull Attempt");
}
}
public void viewDetail(View view)
{
MessagePopper.message(this, help.getAllData());
}
public void viewUserDetail(View view)
{
MessagePopper.message(this, help.getSpecificData(infoFetcher.getText().toString()));
}
public void updateUserDetail(View view)
{
MessagePopper.message(this, "Updated number of rows are "+help.updateRow(name.getText().toString(),infoFetcher.getText().toString()));
}
public void deleteUserDetail(View view)
{
MessagePopper.message(this, "Deleted number of rows are "+help.deleteRow(infoFetcher.getText().toString()));
}
}
Database Adapter class
package com.example.sqlitedbtestproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AryaDatabaseAdapter
{
Context context;
DBHelper helpDB;
AryaDatabaseAdapter(Context ctx)
{
helpDB = new DBHelper(ctx);
}
public Long insertData(String name, String address)
{ System.out.println("Reached inside insert data ");
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, name);
contentValues.put(DBHelper.ADDRESS, address);
SQLiteDatabase db = helpDB.getWritableDatabase();
Long l = db.insert(DBHelper.TABLE_NAME, null, contentValues);
System.out.println("Reached inside insert data "+l+" "+name+" "+address);
return l;
}
public String getAllData()
{ System.out.println("Reached inside get data ");
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID,DBHelper.NAME, DBHelper.ADDRESS};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , null,null,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
buff.append(cursor.getInt(cursor.getColumnIndex(DBHelper.UID))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.NAME))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS))+" \n ");
}
return buff.toString();
}
public String getSpecificData(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID, DBHelper.ADDRESS};
System.out.println("Name is "+name);
String []selectionArgs = {name};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , DBHelper.NAME+" =? ",selectionArgs,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
String address = cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS));
buff.append(id+" "+address+" \n ");
}
return buff.toString();
}
public int updateRow(String oldname , String newName)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, newName);
String whereArgs[] = {oldname};
return db.update(DBHelper.TABLE_NAME, contentValues, DBHelper.NAME + " =? ", whereArgs);
}
public int deleteRow(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String whereArgs[] = {name};
return db.delete(DBHelper.TABLE_NAME, DBHelper.NAME + " =? ", whereArgs);
}
static class DBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "aryadatabase";
private final static String TABLE_NAME = "ARYATABLE";
private final static int DATABASE_VERSION = 1;
private final static String UID = "_id";
private final static String NAME = "Name";
private final static String ADDRESS = "Address";
private final static String CREATE = "CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+ADDRESS+" VARCHAR(255));";
private final static String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
Context context ;
public DBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
MessagePopper.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
//CREATE TABLE ARYATABLE (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(255));
try
{
db.execSQL(CREATE);
MessagePopper.message(context, "OnCreate Called");
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try
{
db.execSQL(DROP_TABLE);
MessagePopper.message(context, "OnUpgarde Called");
onCreate(db);
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
}
}
Message or Toast popper example
package com.example.sqlitedbtestproject;
import android.content.Context;
import android.widget.Toast;
public class MessagePopper {
public static void message(Context ctx, String Message)
{
Toast.makeText(ctx, Message, Toast.LENGTH_SHORT).show();
}
}
Layout File
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Name :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="19dp"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="18dp"
android:onClick="addUser"
android:text="Add User" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="14dp"
android:onClick="viewDetail"
android:text="View Details" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:ems="10"
android:hint="Name of person for details" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText3"
android:layout_alignRight="#+id/editText3"
android:layout_below="#+id/editText3"
android:onClick="viewUserDetail"
android:text="View User Address" />
<Button
android:id="#+id/button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_alignParentBottom="true"
android:layout_marginBottom="17dp"
android:onClick="updateUserDetail"
android:text="Update" />
<Button
android:id="#+id/button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button4"
android:layout_centerHorizontal="true"
android:onClick="deleteUserDetail"
android:text="Delete" />
</RelativeLayout>
View this sample code i have developed and verify against your code. You should upload logcat for precise solution here. :)

Categories