Comparing the User Input Edit Text with SQLite Database Android Java - java

Hello I am making a teacher assistant app, the app uses SQLite database and allows teacher to take attendance by adding updating and removing students, the student ID is generated everytime a new student is added, now here is the thing how to display error message if the input from the teacher doesn't match a student ID in database instead of making my app crash.
StudentOperations
package com.appcreator.isa.theteacherassistantapp.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
import java.util.ArrayList;
import java.util.List;
public class StudentOperations
{
public static final String LOGTAG = "STD_MNGMNT_SYS";
SQLiteOpenHelper dbhandler;
SQLiteDatabase database;
private static final String[] allColumns = {
StudentDatabaseHandler.COLUMN_SID,
StudentDatabaseHandler.COLUMN_EID,
StudentDatabaseHandler.COLUMN_FIRST_NAME,
StudentDatabaseHandler.COLUMN_LAST_NAME,
StudentDatabaseHandler.COLUMN_STUDY,
StudentDatabaseHandler.COLUMN_ATTENDANCE
};
public StudentOperations(Context context)
{
dbhandler = new StudentDatabaseHandler(context);
}
public void open()
{
Log.i(LOGTAG,"Database Opened");
database = dbhandler.getWritableDatabase();
}
public void close()
{
Log.i(LOGTAG, "Database Closed");
dbhandler.close();
}
public Student addStudent(Student Student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, Student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME,Student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME,Student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, Student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, Student.getAttendance());
long insertSID = database.insert(StudentDatabaseHandler.TABLE_STUDENTS,null,values);
Student.setStudentID(insertSID);
return Student;
}
// Getting single Student
public Student getStudent(long id)
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,StudentDatabaseHandler.COLUMN_SID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
if (cursor != null)
cursor.moveToFirst();
Student e = new Student(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
// return Student
return e;
}
public List<Student> getAllStudents()
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,null,null,null, null, null);
List<Student> students = new ArrayList<>();
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
Student student = new Student();
student.setStudentID(cursor.getLong(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_SID)));
student.setEnrlomentID(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_EID)));
student.setFirstname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_FIRST_NAME)));
student.setLastname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_LAST_NAME)));
student.setStudy(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_STUDY)));
student.setAttendance(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_ATTENDANCE)));
students.add(student);
}
}
// return All Students
return students;
}
// Updating Student
public int updateStudent(Student student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME, student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME, student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, student.getAttendance());
// updating row
return database.update(StudentDatabaseHandler.TABLE_STUDENTS, values,
StudentDatabaseHandler.COLUMN_SID + "=?",new String[] { String.valueOf(student.getStudentID())});
}
// Deleting Student
public void removeStudent(Student student)
{
database.delete(StudentDatabaseHandler.TABLE_STUDENTS, StudentDatabaseHandler.COLUMN_SID + "=" + student.getStudentID(), null);
}
}
The Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent(){
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}
Logcat
10-17 03:42:09.750 11105-11105/com.appcreator.isa.theteacherassistantapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appcreator.isa.theteacherassistantapp, PID: 11105
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.appcreator.isa.theteacherassistantapp.Database.StudentOperations.getStudent(StudentOperations.java:71)
at com.appcreator.isa.theteacherassistantapp.MainActivity$5.onClick(MainActivity.java:144)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Updated Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
private static final String TAG = "Student Exits";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public boolean check_existence(String stud_id)
{
SQLiteOpenHelper db = new StudentDatabaseHandler(this);
SQLiteDatabase database = db.getWritableDatabase();
String select = "SELECT * FROM students WHERE studentID =" + stud_id;
Cursor c = database.rawQuery(select, null);
if (c.moveToFirst())
{
Log.d(TAG,"Student Exists");
return true;
}
if(c!=null)
{
c.close();
}
database.close();
return false;
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
final View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
else
{
// get user input and set it to result
// edit text
if (check_existence(userInput.getText().toString()) == true)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
else
{
if(check_existence(userInput.getText().toString()) == true)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Invalid Input" , Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}

You can make a new method to do the work with boolean data type and if it returns false, you might want to display it to the user via Toast or anything like that.
It may look like this in code:
public boolean check_existence(String stud_id) {
SQLiteDatabase db = this.getWritableDatabase();
String select = "SELECT * FROM table_name WHERE column_name ='" + stud_id;
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
Log.d(TAG,"User exits");
return true;
}
if(c!=null) {
c.close();
}
db.close();
return false;
}
You can now just call the method and if it returns false you may just display what you want using Toast.

Related

Why is my .putExtra not passing information?

I am creating an app similar to a notes app. I have an activity that is called AddEditUserActivity, and, as its name implies, it adds OR edits a user (the object that I created). When I click on a user on the RecyclerView, I am supposed to go to the AddEditUserActivity and see the 5 fields full with the info of the selected user with the title of the activity as "Edit User". When I create a new user, I am supposed to go to the same activity, but with the fields empty, and "Add User" as the title. Creating a user works fine, but when I try to edit it, the activity appears with "Add User" as a title and all the fields empty.
The strange thing is that I implemented some Toast messages like "User updated" and "User Created", and they show when they are supposed to. I think that the problem is in the MainActivity. When I click on a user, I putExtra to an Intent and then call startActivityForResult(EDIT_USER_REQUEST, intent). In the AddEditUserActivity, inside onCreate, I specified that if the intent has a specific extra (the id) then it means that I am updating the user. But it ignores that part. So I would really appreciate it if you could help me.
Here is my MainActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int ADD_USER_REQUEST = 1;
public static final int EDIT_USER_REQUEST = 2;
private UserViewModel userViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton addUserButton = findViewById(R.id.button_add_user);
addUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
startActivityForResult(intent, ADD_USER_REQUEST);
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final UserAdapter adapter = new UserAdapter();
recyclerView.setAdapter(adapter);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.getAllUsers().observe(this, new Observer<List<User>>() {
#Override
public void onChanged(#Nullable List<User> users) {
adapter.submitList(users);
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
userViewModel.delete(adapter.getUserAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "User deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
adapter.setOnItemClickListener(new UserAdapter.OnItemClickListener() {
#Override
public void onItemClick(User user) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
intent.putExtra(AddEditUserActivity.EXTRA_ID, user.getId());
intent.putExtra(AddEditUserActivity.EXTRA_NAME, user.getName());
intent.putExtra(AddEditUserActivity.EXTRA_FAMILY, user.getFamily());
intent.putExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE, user.getLicensePlate());
intent.putExtra(AddEditUserActivity.EXTRA_DOCUMENT, user.getDocument());
intent.putExtra(AddEditUserActivity.EXTRA_ADDRESS, user.getAddress());
intent.putExtra(AddEditUserActivity.EXTRA_TIME, user.getTime());
startActivityForResult(intent, EDIT_USER_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
userViewModel.insert(user);
Toast.makeText(this, "User saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
int id = data.getIntExtra(AddEditUserActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "User couldn't be updated", Toast.LENGTH_SHORT).show();
return;
}
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
user.setId(id);
userViewModel.update(user);
Toast.makeText(this, "User updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "User not saved", Toast.LENGTH_SHORT).show();
}
}
}
And here the AddEditUserActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.time.LocalDateTime;
import java.util.Objects;
public class AddEditUserActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.citadelentrance.EXTRA_ID";
public static final String EXTRA_NAME = "com.example.citadelentrance.EXTRA_NAME";
public static final String EXTRA_FAMILY = "com.example.citadelentrance.EXTRA_FAMILY";
public static final String EXTRA_LICENSE_PLATE = "com.example.citadelentrance.EXTRA_LICENSE_PLATE";
public static final String EXTRA_DOCUMENT = "com.example.citadelentrance.EXTRA_DOCUMENT";
public static final String EXTRA_ADDRESS = "com.example.citadelentrance.EXTRA_ADDRESS";
public static final String EXTRA_TIME = "com.example.citadelentrance.EXTRA_TIME";
private EditText editTextName, editTextFamily,
editTextLicensePlate, editTextDocument, editTextAddress;
private TextView textViewTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
editTextName = findViewById(R.id.edit_text_name);
editTextFamily = findViewById(R.id.edit_text_family);
editTextLicensePlate = findViewById(R.id.edit_text_license_plate);
editTextDocument = findViewById(R.id.edit_text_document);
editTextAddress = findViewById(R.id.edit_text_address);
textViewTime = findViewById(R.id.text_view_time);
Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.drawable.ic_close);
Intent intent = new Intent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit User");
editTextName.setText(intent.getStringExtra(EXTRA_NAME));
editTextFamily.setText(intent.getStringExtra(EXTRA_FAMILY));
editTextLicensePlate.setText(intent.getStringExtra(EXTRA_LICENSE_PLATE));
editTextDocument.setText(intent.getStringExtra(EXTRA_DOCUMENT));
editTextAddress.setText(intent.getStringExtra(EXTRA_ADDRESS));
textViewTime.setText(intent.getStringExtra(EXTRA_TIME));
} else {
setTitle("Add User");
textViewTime.setText(LocalDateTimeConverter.toDateString(LocalDateTime.now()));
Log.println(Log.ASSERT, "CS50x", "Add user activity");
}
}
private void saveUser() {
String name = getTextFromEdit(editTextName);
String family = getTextFromEdit(editTextFamily);
String licensePlate = getTextFromEdit(editTextLicensePlate);
String document = getTextFromEdit(editTextDocument);
String address = getTextFromEdit(editTextAddress);
String time = textViewTime.toString();
if (name.isEmpty() || family.isEmpty() || licensePlate.isEmpty() ||
document.isEmpty() || address.isEmpty()) {
Toast.makeText(this, "Please don't leave empty fields", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_NAME, name);
data.putExtra(EXTRA_FAMILY, family);
data.putExtra(EXTRA_LICENSE_PLATE, licensePlate);
data.putExtra(EXTRA_DOCUMENT, document);
data.putExtra(EXTRA_ADDRESS, address);
data.putExtra(EXTRA_TIME, time);
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if (id != -1) {
data.putExtra(EXTRA_ID, id);
Log.println(Log.ASSERT, "CS50x", "id != -1");
}
setResult(RESULT_OK, data);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_save_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.save_user) {
saveUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private String getTextFromEdit(EditText editText) {
return editText.getText().toString().trim();
}
}
#arget's comment is correct - you need to change this:
Intent intent = new Intent();
to this
Intent intent = getIntent();
or use it directly instead.
Another thing, why don't you make the user class implement Parcelable, and pass the user around instead of all its properties? It would make the code a cleaner.

How to delete all RecyclerView items from SQLite Database?

I am a beginner at coding in Java. I am creating a notes app with lots of other features. And one of the features are, storing the user's bank card details in a RecyclerView. I did this by making an SQLite CRUD. All of the Create, Read, Update and Delete works. And I protected this page with a Pattern lock.
And when we are in the Input Pattern page, we can see a clickable text called Click HERE if you forgot your pattern, That works. And when you click on that clickable text, the app shows an Alert Dialog, titled are you sure? and the message is If you change your pattern, all your data will be deleted then there are two buttons Yes and No. No does nothing, it just cancel the forgot pattern thing. But the problem is with the Yes button.
When we click it, It should delete all bank cards or delete all data. Please suggest a way to delete all data from the SQLite Database. I tried lots of ways to do this.
HERE IS MY INPUT PATTERN ACTIVITY
package com.ixidev.simplenotepad;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ixidev.simplenotepad.model.Note;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProgramActivity extends AppCompatActivity {
FloatingActionButton fab, fabChangePattern, fabexit;
RecyclerView mRecyclerViewBC;
CardsDatabaseHelper cardsDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
mRecyclerViewBC = findViewById(R.id.recyclerViewBC);
cardsDatabaseHelper = new CardsDatabaseHelper(this);
showRecord();
fabexit = findViewById(R.id.exitProgram);
fab = findViewById(R.id.addFabButtonBC);
fabChangePattern = findViewById(R.id.ChangePattern);
fabexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, MainActivity.class);
startActivity(intent);
}
});
fabChangePattern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, CreatePasswordActivity.class);
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, AddBankCardActivity.class);
intent.putExtra("BCeditMode", false);
startActivity(intent);
}
});
}
private void showRecord() {
CardAdapter cardAdapter = new CardAdapter(ProgramActivity.this, cardsDatabaseHelper.getAllBCdata(ConstantsCard.BC_C_ADD_TIMESTAMP + " DESC"));
mRecyclerViewBC.setAdapter(cardAdapter);
}
#Override
protected void onResume() {
super.onResume();
showRecord();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
}
HERE IS MY DATABASE HELPER CLASS
package com.ixidev.simplenotepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CardsDatabaseHelper extends SQLiteOpenHelper {
public CardsDatabaseHelper(#Nullable Context context) {
super(context, ConstantsCard.BC_DB_NAME, null, ConstantsCard.BC_DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ConstantsCard.BC_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ConstantsCard.BC_TABLE_NAME);
onCreate(db);
}
public long insertInfo(String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
long id = db.insert(ConstantsCard.BC_TABLE_NAME, null, values);
db.close();
return id;
}
public void updateInfo(String BCid, String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
db.update(ConstantsCard.BC_TABLE_NAME, values, ConstantsCard.BC_C_ID + " = ?", new String[]{BCid});
db.close();
}
public void deleteInfo(String BCid) {
SQLiteDatabase db = getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME, ConstantsCard.BC_C_ID + " = ? ", new String[]{BCid});
db.close();
}
public void testDelete() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME,null,null);
db.execSQL("delete from "+ ConstantsCard.BC_TABLE_NAME);
db.execSQL("TRUNCATE table " + ConstantsCard.BC_TABLE_NAME);
db.close();
}
public void delete(String BCid)
{
String[] args={BCid};
getWritableDatabase().delete("texts", "_ID=?", args);
}
public ArrayList<CardModel> getAllBCdata(String orderByBC) {
ArrayList<CardModel> ArrayListCard = new ArrayList<>();
String selectQuery = "SELECT * FROM " + ConstantsCard.BC_TABLE_NAME + " ORDER BY " + orderByBC;
SQLiteDatabase BCdb = this.getWritableDatabase();
Cursor CardCursor = BCdb.rawQuery(selectQuery, null);
if (CardCursor.moveToNext()) {
do {
CardModel cardModel = new CardModel(
""+CardCursor.getInt(CardCursor.getColumnIndex(ConstantsCard.BC_C_ID)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_IMAGE)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_NUMBER)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_CVV)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_EXPIRY)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_ADD_TIMESTAMP)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_UPDATE_TIMESTAMP))
);
ArrayListCard.add(cardModel);
} while (CardCursor.moveToNext());
}
BCdb.close();
return ArrayListCard;
}
}
HERE IS MY ADAPTER CLASS
package com.ixidev.simplenotepad;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.arch.core.executor.TaskExecutor;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.Holder> {
private Context CardContext;
private ArrayList<CardModel> CardArrayList;
CardsDatabaseHelper cardsDatabaseHelper;
public CardAdapter(Context cardContext, ArrayList<CardModel> cardArrayList) {
CardContext = cardContext;
CardArrayList = cardArrayList;
cardsDatabaseHelper = new CardsDatabaseHelper(CardContext);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View viewBC = LayoutInflater.from(CardContext).inflate(R.layout.bc_row, parent, false);
return new Holder(viewBC);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
CardModel cardModel = CardArrayList.get(position);
final String BCid = cardModel.getBCid();
final String BCimage = cardModel.getImageBC();
final String BCnumber = cardModel.getNumber();
final String BCcvv = cardModel.getCvv();
final String BCexpiry = cardModel.getExpiryBC();
final String addTimeStampBC = cardModel.getAddTimeStampBC();
final String updateTimeStampBC = cardModel.getUpdateTimeStampBC();
holder.profileIvBC.setImageURI(Uri.parse(BCimage));
holder.number.setText(BCnumber);
holder.cvv.setText(BCcvv);
holder.expiryBC.setText(BCexpiry);
holder.editButtonBC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDialog(
""+position,
""+BCid,
""+BCnumber,
""+BCcvv,
""+BCexpiry,
""+BCimage,
""+addTimeStampBC,
""+updateTimeStampBC
);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
deleteDialog(
""+BCid
);
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CardContext, "Clicked", Toast.LENGTH_SHORT).show();
cardsDatabaseHelper.testDelete();
cardsDatabaseHelper.delete(BCid);
}
});
}
private void deleteDialog(final String BCid) {
AlertDialog.Builder builderBC = new AlertDialog.Builder(CardContext);
builderBC.setTitle("Delete?");
builderBC.setMessage("Are you sure you want to delete this document?");
builderBC.setCancelable(false);
builderBC.setIcon(R.drawable.ic_action_delete);
builderBC.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
cardsDatabaseHelper.deleteInfo(BCid);
((ProgramActivity)CardContext).onResume();
Toast.makeText(CardContext, "Successfully deleted!", Toast.LENGTH_SHORT).show();
}
});
builderBC.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderBC.create().show();
}
private void editDialog(String position, String BCid, String BCnumber, String BCcvv, String BCexpiry, String BCimage, String addTimeStampBC, String updateTimeStampBC) {
AlertDialog.Builder BCbuilder = new AlertDialog.Builder(CardContext);
BCbuilder.setTitle("Edit?");
BCbuilder.setMessage("Are you sure you want to edit this Bank Card?");
BCbuilder.setCancelable(false);
BCbuilder.setIcon(R.drawable.ic_action_edit);
BCbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CardContext, EditBankCardActivity.class);
intent.putExtra("BCID", BCid);
intent.putExtra("NUMBER", BCnumber);
intent.putExtra("CVV", BCcvv);
intent.putExtra("EXPIRYBC", BCexpiry);
intent.putExtra("IMAGE", BCimage);
intent.putExtra("BC_ADD_TIMESTAMP", addTimeStampBC);
intent.putExtra("BC_UPDATE_TIMESTAMP", updateTimeStampBC);
intent.putExtra("BCeditMode", true);
CardContext.startActivity(intent);
}
});
BCbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
BCbuilder.create().show();
}
#Override
public int getItemCount() {
return CardArrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIvBC;
TextView number, cvv, expiryBC;
ImageButton editButtonBC;
public Holder(#NonNull View itemView) {
super(itemView);
profileIvBC = itemView.findViewById(R.id.profileIvBC);
number = itemView.findViewById(R.id.number);
cvv = itemView.findViewById(R.id.cvv);
expiryBC = itemView.findViewById(R.id.expiry);
editButtonBC = itemView.findViewById(R.id.editBtnBC);
}
}
}
HERE IS MY MODEL CLASS
package com.ixidev.simplenotepad;
public class CardModel {
String BCid, imageBC, number, cvv, expiryBC, addTimeStampBC, updateTimeStampBC;
public CardModel(String BCid, String imageBC, String number, String cvv, String expiryBC, String addTimeStampBC, String updateTimeStampBC) {
this.BCid = BCid;
this.imageBC = imageBC;
this.number = number;
this.cvv = cvv;
this.expiryBC = expiryBC;
this.addTimeStampBC = addTimeStampBC;
this.updateTimeStampBC = updateTimeStampBC;
}
public String getBCid() {
return BCid;
}
public void setBCid(String BCid) {
this.BCid = BCid;
}
public String getImageBC() {
return imageBC;
}
public void setImageBC(String imageBC) {
this.imageBC = imageBC;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getExpiryBC() {
return expiryBC;
}
public void setExpiryBC(String expiryBC) {
this.expiryBC = expiryBC;
}
public String getAddTimeStampBC() {
return addTimeStampBC;
}
public void setAddTimeStampBC(String addTimeStampBC) {
this.addTimeStampBC = addTimeStampBC;
}
public String getUpdateTimeStampBC() {
return updateTimeStampBC;
}
public void setUpdateTimeStampBC(String updateTimeStampBC) {
this.updateTimeStampBC = updateTimeStampBC;
}
}
And here is my CONSTANTS class
package com.ixidev.simplenotepad;
public class ConstantsCard {
public static final String BC_DB_NAME = "MY_BANK_CARDS";
public static final int BC_DB_VERSION = 1;
public static final String BC_TABLE_NAME = "MY_BANK_CARDS_TABLE";
public static final String BC_C_ID = "BC_ID";
public static final String BC_C_NUMBER = "BC_NUMBER";
public static final String BC_C_CVV = "BC_CVV";
public static final String BC_C_EXPIRY = "BC_EXPIRY";
public static final String BC_C_IMAGE = "BC_IMAGE";
public static final String BC_C_ADD_TIMESTAMP = "BC_ADD_TIMESTAMP";
public static final String BC_C_UPDATE_TIMESTAMP = "BC_UPDATE_TIMESTAMP";
public static final String BC_CREATE_TABLE = "CREATE TABLE " + BC_TABLE_NAME + "("
+ BC_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BC_C_NUMBER + " TEXT,"
+ BC_C_CVV + " TEXT,"
+ BC_C_EXPIRY + " TEXT,"
+ BC_C_IMAGE + " TEXT,"
+ BC_C_ADD_TIMESTAMP + " TEXT,"
+ BC_C_UPDATE_TIMESTAMP + " TEXT"
+ ");";
}

How to read and display user's rank which is set as default in the beginning

I added a new column COL_5 to my SQLite database and it's called "rank". Every user registered starts with rank set as "Australopithecus afarensis" which should be displayed in UserPanelActivity.java. What I did is I managed to display nickname of user (SignInActivity) but I have trouble with checking current rank and then display it on the screen.
Code looks like this:
DatabaseHelper:
package com.pracainzynierska.inzynierka;
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;
import android.widget.TextView;
import androidx.annotation.Nullable;
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 ="mail_address";
public static final String COL_4 ="password";
public static final String COL_5 = "rank";
//public static final String COL_6 = "dailytip";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME,null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT, mail_address TEXT, password TEXT, rank TEXT DEFAULT 'Australopithecus afarensis')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addUser(String user, String password, String mail_address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", user);
contentValues.put("password", password);
contentValues.put("mail_address", mail_address);
long res = db.insert("registeruser", null, contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password)
{
String[] columns = {COL_1};
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;
}
}
SignInActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
public class SignInActivity extends AppCompatActivity {
private TextView register_text;
public static CallbackManager callbackManager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
db = new DatabaseHelper(this);
callbackManager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
usernameEditText.requestFocus();
register_text = findViewById(R.id.register_text);
register_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(SignInActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = usernameEditText.getText().toString().trim();
String pwd = passwordEditText.getText().toString().trim();
Boolean res = db.checkUser(user,pwd);
if(res == true)
{
Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
Intent intentPopUp = new Intent(SignInActivity.this, PopUpActivity.class);
intent.putExtra("username",user);
startActivity(intent);
startActivity(intentPopUp);
Toast.makeText(SignInActivity.this,"Welcome " + user + "!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"There is a problem with singing in!", Toast.LENGTH_SHORT).show();
usernameEditText.setText("");
passwordEditText.setText("");
usernameEditText.requestFocus();
}
}
});
}
}
UserPanelActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserPanelActivity extends AppCompatActivity {
private Button settings_btn, progress_btn, dailychallenge_btn, premium_btn, logout_btn, training_btn;
private TextView NickNameText, rankText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_panel);
String username = getIntent().getStringExtra("username");
//String rank = getIntent().getStringExtra("rank");
NickNameText = findViewById(R.id.nickname);
NickNameText.setText(username);
//here I'd like to display rank
rankText = findViewById(R.id.rank);
rankText.setText(rank);
settings_btn = findViewById(R.id.settings_user_panel_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Settings();
}
});
progress_btn = findViewById(R.id.progress_button);
progress_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyProgress();
}
});
dailychallenge_btn = findViewById(R.id.challenge_button);
dailychallenge_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DailyChallenge();
}
});
premium_btn = findViewById(R.id.premium_button);
premium_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Premium();
}
});
logout_btn = findViewById(R.id.logout_button);
logout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackToMenu();
finish();
}
});
training_btn = findViewById(R.id.start_freetraining_button);
training_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Training();
}
});
}
private void Training() {
Intent intent = new Intent(this, FillTheTextActivity.class);
startActivity(intent);
}
private void BackToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void Premium() {
Intent intent = new Intent(this,PremiumActivity.class);
startActivity(intent);
}
private void DailyChallenge() {
Intent intent = new Intent(this,DailyChallengeActivity.class);
startActivity(intent);
}
private void MyProgress() {
Intent intent = new Intent(this,MyProgressActivity.class);
startActivity(intent);
}
private void Settings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
Every help is kindly seen, thanks in advance :)
Create a method like this in your DatabaseHelper class:
public String getRank(int id) {
String query = "SELECT rank from " + TABLE_NAME + " where ID = " + id;
SQLiteDatabase db = getReadableDatabase();
try {
return db.rawQuery(query, null).getString(cursor.getColumnIndex(rank));
} catch (Exception e) {
return "";
}
}
Source

Database isn't loaded on first run API 26

I created an app with database in assets folder . I wrote a code to copy database to SD Card and of course for android 6 + it needs run time permission. My problem : on first run after granting permission database isn't loaded but on second run there is no problem. Please help me to solve this issue .
UPDATE: Problem solved! now I have problem with favorite section. when I add something to favorite it can't be updated and I have to restart app and also with each run data is shown more than one time.
Here's my code :
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else {
setupDB();
selectList();
selectFavorite();
Toast.makeText(MainActivity.this, "You grandet earlier",
Toast.LENGTH_LONG).show();
}
}
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}
if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this,
ActivitySearch.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length >= 2 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Access granted",
Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
You have just shown a toast after permissions are granted for the first time i.e. inside onRequestPermissionsResult. You will need to place the code to perform necessary operations inside there too.

Check if value entered exists in database android

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

Categories

Resources