ListView editable OnLongClickListener - java

I have been searching for hours but still I can't find any way on how to update a listview using the listview.setOnItemLongClickListener I have tried but I think I am doing it all wrong. Does anyone know how to edit a listview after a longclick listener?
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String TEST_TABLE = "TEST_TABLE";
public static final String TEST_NAME = "NAME";
public static final String COLUMN_NAME = TEST_NAME;
public static final String COLUMN_ADDRESS = "ADDRESS";
public static final String COLUMN_ID = "ID";
public static final String TEST_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, "test.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTableStatement = "CREATE TABLE " + TEST_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_ADDRESS + " TEXT)";
sqLiteDatabase.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public boolean addData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, testModel.getName());
cv.put(COLUMN_ADDRESS, testModel.getAddress());
long insert = db.insert(TEST_TABLE, null, cv);
if (insert == -1) {
return false;
} else {
return true;
}
}
public boolean deleteData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM " + TEST_TABLE + " WHERE " + COLUMN_ID + " = " + testModel.getID();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
return true;
} else {
return false;
}
}
public void update(TestModel testModel) {
}
public List<TestModel> viewAll() {
List<TestModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + TEST_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
TestModel newTest = new TestModel(id, name, address);
returnList.add(newTest);
} while (cursor.moveToNext());
} else {
}
cursor.close();
db.close();
return returnList;
}
}
TestModel
public class TestModel {
private int ID;
private String name;
private String address;
public TestModel(int ID, String name, String address) {
this.ID = ID;
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "ID:" + ID +
", name:'" + name + '\'' +
", address:'" + address + '\'' +
'}';
}
public TestModel() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
MainActivity
package com.example.crudtest2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btn_Add, btn_View;
EditText et_name, et_address, et_username;
ListView lv_allList;
ArrayAdapter testArrayAdapter;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_Add = findViewById(R.id.btnAdd);
btn_View = findViewById(R.id.btnView);
et_name = findViewById(R.id.inputName);
et_address = findViewById(R.id.inputAddress);
lv_allList = findViewById(R.id.listviewData);
dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
btn_Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TestModel testModel;
try {
testModel = new TestModel(-1, et_name.getText().toString(), et_address.getText().toString());
Toast.makeText(MainActivity.this, "Successfully Added", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error adding", Toast.LENGTH_SHORT).show();
testModel = new TestModel(-1, "error", "error");
}
DBHelper dbHelper = new DBHelper(MainActivity.this);
dbHelper.addData(testModel);
showAllData(dbHelper);
}
});
btn_View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBHelper dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
//Toast.makeText(MainActivity.this, dbHelper.viewAll().toString(), Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.deleteData(clickedData);
showAllData(dbHelper);
Toast.makeText(MainActivity.this, "Data Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.updateData(clickedData);
return true;
}
});
}
private void showAllData(DBHelper dbHelper) {
testArrayAdapter = new ArrayAdapter<TestModel>(MainActivity.this, android.R.layout.simple_list_item_1, dbHelper.viewAll());
lv_allList.setAdapter(testArrayAdapter);
}
}
Is there like any way to edit my listview once a longclick listener event has happened? I have tried doing the same thing with delete it's because I don't have really any idea how to edit a listview after a longclick.

Related

setAdapter() crashes android app in android studio

I'm following this tutorial (https://www.youtube.com/watch?v=hDSVInZ2JCs&t=3615s&ab_channel=SoftwareandProgrammingwithProfessorSluiter)
Everything works great, until I try this line of code :
lv_productList.setAdapter(productArrayAdapter);
then the app crashes. I've looked online and tried a bunch of stuff but I'm super stuck
Here's the problem area
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
here's my full code
MainActivity.java
package com.example.sqldemo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//reference to all buttons and controls on the layout
Button btn_add, btn_viewAll;
EditText et_name, et_number;
ListView lv_productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add = findViewById(R.id.btn_add);
btn_viewAll = findViewById(R.id.btn_viewAll);
et_name = findViewById(R.id.et_name);
et_number = findViewById(R.id.et_number);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductModel productModel;
try {
productModel = new ProductModel(-1, et_name.getText().toString(), Integer.parseInt(et_number.getText().toString()));
Toast.makeText(MainActivity.this, productModel.toString(), Toast.LENGTH_SHORT).show();
}
catch(Exception err) {
Toast.makeText(MainActivity.this, "Error creating product", Toast.LENGTH_SHORT).show();
productModel = new ProductModel(-1, "error", 0);
}
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = dataBaseHelper.addOne(productModel);
Toast.makeText(MainActivity.this, "Success! Product has been added to the database :)", Toast.LENGTH_SHORT).show();
}
});
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
DataBaseHelper.java
package com.example.sqldemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COLUMN_PRODUCT_NAME = "PRODUCT_NAME";
public static final String COLUMN_PRODUCT_NUMBER = "PRODUCT_AGE";
public static final String COLUMN_ID = "ID";
public DataBaseHelper(#Nullable Context context) {
super(context, "Products.db", null, 1);
}
//this is called the first item a database is accessed. used to create a new database
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + PRODUCT_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_PRODUCT_NAME + " TEXT, " + COLUMN_PRODUCT_NUMBER + " INT)";
db.execSQL(createTableStatement);
}
//this is called if the database version number changes. It prevents previous users apps from breaking when the database is updated
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addOne(ProductModel productModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUCT_NAME, productModel.getName());
cv.put(COLUMN_PRODUCT_NUMBER, productModel.getNumber());
//long insert returns positive in data insertion was successful, and negative if it was not
long insert = db.insert(PRODUCT_TABLE, null, cv);
if (insert == -1) {
return false;
}
else {
return true;
}
}
public List<ProductModel> getAll() {
List<ProductModel> returnList = new ArrayList<>();
// get data from the database
String queryString = "SELECT * FROM " + PRODUCT_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
//move the cursor to the first set of data and check if anything was returned
if (cursor.moveToFirst()) {
// loop through the cursor (result set) and create new product objects. Put them into the return list (defined above)
do {
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
int productNumber = cursor.getInt(2);
ProductModel newProduct = new ProductModel(productID, productName, productNumber);
returnList.add(newProduct);
} while (cursor.moveToNext());
}
else {
//if no results from database, don't add anything to the list.
}
cursor.close();
db.close();
return returnList;
}
}
ProductModel.java
package com.example.sqldemo;
//declare a new public class/object with 3 variables
public class ProductModel {
private int id;
private String name;
private int number;
//constructor
public ProductModel(int id, String name, int number) {
this.id = id;
this.name = name;
this.number = number;
}
public ProductModel() {
}
// toString is necessary for printing the contents of a class object
#Override
public String toString() {
return "ProductModel{" +
"id=" + id +
", name='" + name + '\'' +
", number=" + number +
'}';
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
> Blockquote
You can simply change RecyclerView to ListView.
Or
if you want to use RecyclerView, you have to create a custom Recyclerview Adapter.
Here a Beginner friendly Guide: https://medium.com/#suhanshupatel/recyclerview-in-android-for-beginner-cfbc132a0dec

How to implement searchview in recyclerview which based on SQLite? - Android

I am Building Android application which stores the patient details in SQLite database and shows this data in recyclerview, Now i want to add searchview for my recyclerview, plz help me to implement this one.
I am working on this project with the help of this youtube tutorial Series - https://youtube.com/playlist?list=PLSrm9z4zp4mGK0g_0_jxYGgg3os9tqRUQ
Here is my MainActivity Class
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
_id = new ArrayList<>();
name = new ArrayList<>();
disease = new ArrayList<>();
medicine = new ArrayList<>();
mobile = new ArrayList<>();
address = new ArrayList<>();
day = new ArrayList<>();
month = new ArrayList<>();
year = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(MainActivity.this, _id, name, disease, medicine, mobile, address, day, month, year);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
_id.add(cursor.getString(0));
name.add(cursor.getString(1));
disease.add(cursor.getString(2));
medicine.add(cursor.getString(3));
mobile.add(String.valueOf(cursor.getLong(4)));
address.add(cursor.getString(5));
day.add(cursor.getString(6));
month.add(cursor.getString(7));
year.add(cursor.getString(8));
}
}
}
}
here is my AddActivity Class
package com.example.myclinic;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AddActivity extends AppCompatActivity {
EditText name_input, disease_input, medicine_input, mobile_input, address_input, day_input, month_input, year_input;
Button add_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name_input = findViewById(R.id.name_input);
disease_input = findViewById(R.id.disease_input);
medicine_input = findViewById(R.id.medicine_input);
mobile_input = findViewById(R.id.mobile_input);
address_input = findViewById(R.id.address_input);
day_input = findViewById(R.id.day_input);
month_input = findViewById(R.id.month_input);
year_input = findViewById(R.id.year_input);
add_button = findViewById(R.id.add_button);
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate = formatter.format(date);
day_input.setText(strDate.substring(0,2));
month_input.setText(strDate.substring(3,5));
year_input.setText(strDate.substring(6,10));
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(name_input.getText().toString()) || TextUtils.isEmpty(disease_input.getText().toString())) {
name_input.setHint("Patient Name* (Mandatory)");
disease_input.setHint("Disease* (Mandatory)");
Toast.makeText(AddActivity.this,
"Failed!", Toast.LENGTH_SHORT).show();
} else {
try {
MyDatabaseHelper myDB = new MyDatabaseHelper(AddActivity.this);
myDB.addPatient(name_input.getText().toString().trim(),
disease_input.getText().toString().trim(),
medicine_input.getText().toString().trim(),
Long.parseLong("0" + mobile_input.getText().toString().trim()),
address_input.getText().toString().trim(),
Integer.parseInt(day_input.getText().toString().trim()),
Integer.parseInt(month_input.getText().toString().trim()),
Integer.parseInt(year_input.getText().toString().trim()));
} catch (Exception e) {
Toast.makeText(AddActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
here is MyDatabaseHelper Class
package com.example.myclinic;
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 com.google.android.material.shape.ShapeAppearanceModel;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "PatientList.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "patients";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_DISEASE = "disease";
private static final String COLUMN_MEDICINES = "medicines";
private static final String COLUMN_MOBILE = "mobile";
private static final String COLUMN_ADDRESS = "address";
private static final String COLUMN_DAY = "day";
private static final String COLUMN_MONTH = "month";
private static final String COLUMN_YEAR = "year";
public MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query =
"CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_DISEASE + " TEXT, " +
COLUMN_MEDICINES + " TEXT, " +
COLUMN_MOBILE + " INTEGER, " +
COLUMN_ADDRESS + " TEXT, " +
COLUMN_DAY + " INTEGER, " +
COLUMN_MONTH + " INTEGER, " +
COLUMN_YEAR + " INTEGER);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, pname);
cv.put(COLUMN_DISEASE, pdisease);
cv.put(COLUMN_MEDICINES, pmedicines);
cv.put(COLUMN_MOBILE, pmobile.longValue());
cv.put(COLUMN_ADDRESS, paddress);
cv.put(COLUMN_DAY, pday);
cv.put(COLUMN_MONTH, pmonth);
cv.put(COLUMN_YEAR, pyear);
long result = db.insert(TABLE_NAME, null, cv);
if(result == -1) {
Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null) cursor = db.rawQuery(query, null);
return cursor;
}
}
here is CustomAdapter Class
package com.example.myclinic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.security.PrivateKey;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private ArrayList _id, name, disease, medicine, mobile, address, day, month, year;
CustomAdapter(Context context, ArrayList _id, ArrayList name, ArrayList disease,
ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year){
this.context = context;
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.id_txt.setText(String.valueOf(_id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.disease_txt.setText(String.valueOf(disease.get(position)));
holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
holder.address_txt.setText(String.valueOf(address.get(position)));
holder.day_txt.setText(String.valueOf(day.get(position)));
holder.month_txt.setText(String.valueOf(month.get(position)));
holder.year_txt.setText(String.valueOf(year.get(position)));
}
#Override
public int getItemCount() {
return _id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
disease_txt = itemView.findViewById(R.id.disease_txt);
medicine_txt = itemView.findViewById(R.id.medicine_txt);
mobile_txt = itemView.findViewById(R.id.mobile_txt);
address_txt = itemView.findViewById(R.id.address_txt);
day_txt = itemView.findViewById(R.id.day_txt);
month_txt = itemView.findViewById(R.id.month_txt);
year_txt = itemView.findViewById(R.id.year_txt);
}
}
}
For Implementing search functionality in this project, as #thinkgruen suggested me that i need to work on single arraylist instead of multiple arraylist thats why i created separate class having all my data and made arraylist of that class, and implemented filter method to that arraylist.
After that i gone throgh this youtube tutorial - https://www.youtube.com/watch?v=CTvzoVtKoJ8
I'm posting changed code here, i made old code as a comment and changed code marked as //U . Beacuse U can clearly see what changes i have made.
at first here is new class - PatientList
package com.example.myclinic;
public class PatientList {
private int _id;
private String name;
private String disease;
private String medicine;
private long mobile;
private String address;
private int day;
private int month;
private int year;
private String serialid;
public int getid() {
return _id;
}
public void setid(int _id) {
this._id = _id;
}
public String getname() {
return name;
}
public void setname (String name) {
this.name = name;
}
public String getdisease() {
return disease;
}
public void setdisease (String disease) {
this.disease = disease;
}
public String getmedicine() {
return medicine;
}
public void setmedicine (String medicine) {
this.medicine = medicine;
}
public long getmobile() {
return mobile;
}
public void setmobile (long mobile) {
this.mobile = mobile;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public int getday() {
return day;
}
public void setday(int day) {
this.day = day;
}
public int getmonth() {
return month;
}
public void setmonth(int month) {
this.month = month;
}
public int getyear() {
return year;
}
public void setyear(int year) {
this.year = year;
}
public String getserialid() {
return serialid;
}
public void setserialid (String serialid) {
this.serialid = serialid;
}
//constructor
public PatientList(int _id, String name, String disease, String medicine, long mobile, String address, int day, int month, int year, String serialid){
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
this.serialid = serialid;
}
}
After that, in Class - CustomAdapter
package com.example.myclinic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//U
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> implements Filterable {
private Context context;
// private ArrayList _id, name, disease, medicine, mobile, address, day, month, year, serialid;
private List<PatientList> patientList = new ArrayList<>(); //U
private List<PatientList> patientListAll = new ArrayList<>();
CustomAdapter(Context context,/* ArrayList _id, ArrayList name, ArrayList disease,
ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year, ArrayList serialid, */
ArrayList<PatientList> patientList){
this.context = context;
/*
this._id = _id;
this.name = name;
this.disease = disease;
this.medicine = medicine;
this.mobile = mobile;
this.address = address;
this.day = day;
this.month = month;
this.year = year;
this.serialid = serialid;
*/
this.patientList = patientList; //U
this.patientListAll = new ArrayList<>(patientList);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
/*
holder.id_txt.setText(String.valueOf(_id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.disease_txt.setText(String.valueOf(disease.get(position)));
holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
holder.address_txt.setText(String.valueOf(address.get(position)));
holder.day_txt.setText(String.valueOf(day.get(position)));
holder.month_txt.setText(String.valueOf(month.get(position)));
holder.year_txt.setText(String.valueOf(year.get(position)));
holder.serialid_txt.setText(String.valueOf(serialid.get(position)));
*/
PatientList plist = patientList.get(position); //U
holder.id_txt.setText(String.valueOf(plist.getid()));
holder.name_txt.setText(String.valueOf(plist.getname()));
holder.disease_txt.setText(String.valueOf(plist.getdisease()));
holder.medicine_txt.setText(String.valueOf(plist.getmedicine()));
holder.mobile_txt.setText(String.valueOf(plist.getmobile()));
holder.address_txt.setText(String.valueOf(plist.getaddress()));
holder.day_txt.setText(String.valueOf(plist.getday()));
holder.month_txt.setText(String.valueOf(plist.getmonth()));
holder.year_txt.setText(String.valueOf(plist.getyear()));
holder.serialid_txt.setText(String.valueOf(plist.getserialid()));
}
#Override
public int getItemCount() {
return patientList.size();
}
//U
#Override
public Filter getFilter() {
return filter;
}
//U
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constaint) {
List<PatientList> filteredList = new ArrayList<>();
if (constaint.toString().isEmpty()) {
filteredList.addAll(patientListAll);
} else {
for (PatientList patient : patientListAll) {
if (patient.getname().toLowerCase().contains(constaint.toString().toLowerCase())
|| patient.getserialid().toLowerCase().contains(constaint.toString().toLowerCase())
|| patient.getaddress().toLowerCase().contains(constaint.toString().toLowerCase())) {
filteredList.add(patient);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
patientList.clear();
patientList.addAll((Collection<? extends PatientList>) filterResults.values);
notifyDataSetChanged();
}
};
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt, serialid_txt;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
disease_txt = itemView.findViewById(R.id.disease_txt);
medicine_txt = itemView.findViewById(R.id.medicine_txt);
mobile_txt = itemView.findViewById(R.id.mobile_txt);
address_txt = itemView.findViewById(R.id.address_txt);
day_txt = itemView.findViewById(R.id.day_txt);
month_txt = itemView.findViewById(R.id.month_txt);
year_txt = itemView.findViewById(R.id.year_txt);
serialid_txt = itemView.findViewById(R.id.serialid_txt);
}
}
}
Class DatabaseHelper
package com.example.myclinic;
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 com.google.android.material.shape.ShapeAppearanceModel;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "PatientList.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "patients";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_DISEASE = "disease";
private static final String COLUMN_MEDICINES = "medicines";
private static final String COLUMN_MOBILE = "mobile";
private static final String COLUMN_ADDRESS = "address";
private static final String COLUMN_DAY = "day";
private static final String COLUMN_MONTH = "month";
private static final String COLUMN_YEAR = "year";
private static final String COLUMN_SERIALID = "serialid";
public MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query =
"CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_DISEASE + " TEXT, " +
COLUMN_MEDICINES + " TEXT, " +
COLUMN_MOBILE + " INTEGER, " +
COLUMN_ADDRESS + " TEXT, " +
COLUMN_DAY + " INTEGER, " +
COLUMN_MONTH + " INTEGER, " +
COLUMN_YEAR + " INTEGER, " +
COLUMN_SERIALID + " TEXT);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear, String pserialid){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, pname);
cv.put(COLUMN_DISEASE, pdisease);
cv.put(COLUMN_MEDICINES, pmedicines);
cv.put(COLUMN_MOBILE, pmobile.longValue());
cv.put(COLUMN_ADDRESS, paddress);
cv.put(COLUMN_DAY, pday);
cv.put(COLUMN_MONTH, pmonth);
cv.put(COLUMN_YEAR, pyear);
cv.put(COLUMN_SERIALID, pserialid);
long result = db.insert(TABLE_NAME, null, cv);
if(result == -1) {
Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null) cursor = db.rawQuery(query, null);
return cursor;
}
}
And Final changes in MainActivity.Java
package com.example.myclinic;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SearchView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
// ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year, serialid;
ArrayList<PatientList> patientList = new ArrayList<>(); //U
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
/*
_id = new ArrayList<>();
name = new ArrayList<>();
disease = new ArrayList<>();
medicine = new ArrayList<>();
mobile = new ArrayList<>();
address = new ArrayList<>();
day = new ArrayList<>();
month = new ArrayList<>();
year = new ArrayList<>();
serialid = new ArrayList<>();
*/
storeDataInArray();
customAdapter = new CustomAdapter(MainActivity.this, patientList);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
/*
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
_id.add(cursor.getString(0));
name.add(cursor.getString(1));
disease.add(cursor.getString(2));
medicine.add(cursor.getString(3));
mobile.add(String.valueOf(cursor.getLong(4)));
address.add(cursor.getString(5));
day.add(cursor.getString(6));
month.add(cursor.getString(7));
year.add(cursor.getString(8));
serialid.add(cursor.getString(9));
}
}
} */
void storeDataInArray(){ //U
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
patientList.add(new PatientList(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getLong(4),
cursor.getString(5),
cursor.getInt(6),
cursor.getInt(7),
cursor.getInt(8),
cursor.getString(9)));
}
}
}
#Override //U
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mainmenu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
customAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
nothing changed in AddActivity.
I hope this will be helpfull to you.

How i can get the information from the login of parent (user)

My Parent_home Activity needs data (name, surname, id) from the logged in user, my login activity can only check if the database has the parent(user) credential, and I want after checking if have parent in login activity, parent data from the database gonna given to the Parent_home Activity
DatabaseHelper.java
package edu.angelo.parentsportal;
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;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
public ArrayList<ParentModel> getParentLoginData(String emailOrPhone,String pwd){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "SELECT * FROM " + TABLE_NAME+" WHERE ("+COL_3+"= "+emailOrPhone+" OR "+COL_4 +" = "+emailOrPhone+") AND "+COL_5 +" = "+pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
}
Login.java
package edu.angelo.parentsportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
DatabaseHelper mydb;
SQLiteDatabase sqLiteDatabase;
CustomAdapter customAdapter;
Cursor cursor;
ArrayList<ParentModel> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_register).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
mydb =new DatabaseHelper(this);
sqLiteDatabase = mydb.getReadableDatabase();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email or Phone Number is required");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
else{
progressDialog.setMessage("Please Wait...");
progressDialog.show();
if (mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString()).size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
}
}
}
ParentModel.java (if needed)
package edu.angelo.parentsportal;
public class ParentModel {
public String ID;
public String Name;
public String Surname;
public String Email;
public String Phone_number;
public String Password;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone_number() {
return Phone_number;
}
public void setPhone_number(String phone_number) {
Phone_number = phone_number;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
You can pass the values to the activity using Intent Extras when starting an activity via an Intent.
So you use something like :-
ArrayList<ParentModel> parents = mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString());
if (parents.size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
intent.putExtra("IK_CURRENTPARENTID",parents[0].getId());
intent.putExtra("IK_CURRENTPARENTNAME",parents[0].getName());
intent.putExtra("IK_CURRENTPARENTSURNAME",parents[0].getSurname();
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
You then retrieve the values from the Intent Extras in the Parent_Home activity. using something like in the onCreate method :-
currentId = getIntent().getStringExtra("IK_CURRENTPARENTID");
currentName = getIntent().getStringExtra("IK_CURRENTPARENTNAME");
currentSurName = getIntent().getStringExtra("IK_CURRENTPARENTSURNAME");
noting that the above assumes that currentId, currentName and currentSurName have been declared as class variables.
typically you'd also define constants for the Intent Extra keys rater than hard coding them.
The above is in-principle code, it hasn't been run or tested and may therefore contain some errors.

how to get sqlite connection properly?

If you can check the code and fix the errors in this code
Home.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Home extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
Button loginbtn;
Button registerbtn;
public static final String USERID = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
username_editText = (EditText)findViewById(R.id.home_userName);
password_editText = (EditText)findViewById(R.id.home_password);
loginbtn = (Button)findViewById(R.id.home_loginBtn);
registerbtn = (Button)findViewById(R.id.home_registerBtn);
final DBHandler dbHandler = new DBHandler(Home.this);
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("com.modelpaper.mad.it17121002.ProfileManagement");
startActivity(intent);
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = username_editText.getText().toString();
String password = password_editText.getText().toString();
if(userName.equals("") || password.equals("")){
Toast.makeText(Home.this,"Login Unsuccessful",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(userName);
if(users == null){
Toast.makeText(Home.this,"Invalid username or password",Toast.LENGTH_SHORT).show();
}
else{
int userID = users.getId();
Intent editProfIntent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
editProfIntent.putExtra(USERID,Integer.toString(userID));
startActivity(editProfIntent);
}
}
}
});
}
I think there is error in db class I can't find this error.app is crashed db not created . please try to understand it
DBHandler.java
package com.;
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 java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context) {
super(context, "user_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT UNIQUE," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB +" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB+" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
public boolean addInfo(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
String insertQuery = "INSERT INTO "+UserProfile.Users.TABLE_NAME+"("+UserProfile.Users.COL_USERNAME+","+UserProfile.Users.COL_PASSWORD+","+UserProfile.Users.COL_GENDER+","+
UserProfile.Users.COL_DOB+") VALUES('"+users.getUsername()+"','"+users.getPassword()+"','"+users.getGender()+"','"+users.getDob()+"')";
Log.d("insertQuery",insertQuery);
try {
db.execSQL(insertQuery);
return true;
}
catch (Exception e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
db.close();
return false;
}
public boolean updateInfor(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String username = users.getUsername();
String password = users.getPassword();
String dob = users.getDob();
String gender = users.getGender();
int id = users.getId();
values.put(UserProfile.Users.COL_DOB,dob);
values.put(UserProfile.Users.COL_GENDER,gender);
values.put(UserProfile.Users.COL_PASSWORD,password);
values.put(UserProfile.Users.COL_USERNAME,username);
int result = db.update(UserProfile.Users.TABLE_NAME,values,UserProfile.Users.COL_ID+" = ?",new String[]{String.valueOf(id)});
if(result >0)
return true;
return false;
}
public ArrayList<UserProfile.Users> readAllInfor(){
ArrayList<UserProfile.Users> userList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String readAllQuery = "SELECT * FROM "+UserProfile.Users.TABLE_NAME;
Cursor cursor = db.rawQuery(readAllQuery,null);
if(cursor.moveToFirst()){
do{
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
userList.add(users);
} while (cursor.moveToNext());
}
return userList;
}
public UserProfile.Users readAllInfor(String userName){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME + " = '"+ userName+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public UserProfile.Users readAllInfor(int id){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_ID + " = '"+ id+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public void deleteInfo(String username){
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery = "DELETE FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME +" = '"+ username +"' ";
Log.d("deleteQuery ",deleteQuery);
db.execSQL(deleteQuery);
db.close();
}
}
I checked this one and couldn't find the solution for solve it. This is user profile class to handle user profiles.
UserProfile.java
package com.modelpaper.mad.it17121002;
public final class UserProfile {
private UserProfile(){
}
public static UserProfile getProfile(){
UserProfile userProfile = new UserProfile();
return userProfile;
}
class Users implements BaseColumn{
public static final String TABLE_NAME = "UserInfo";
public static final String COL_ID = "_ID";
public static final String COL_USERNAME = "userName ";
public static final String COL_DOB = "dateOfBirth";
public static final String COL_GENDER = "Gender";
public static final String COL_PASSWORD = "Password";
//displya karana ona variable tika
private int id;
private String username;
private String dob;
private String gender;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//hethuwa-wena thanaka class ekaka wena wenama varible cll krnnaq ona unoth
public Users getUser(){
Users users = new Users();
return users;
}
}
This is edit profile class i have doubt of this class.
EditProfile.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class EditProfile extends AppCompatActivity {
Button searchBtn;
EditText userName_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup genderRadioGroup;
RadioButton genderRadioBtn;
//new Edit
RadioButton genderRadioBtnMale;
RadioButton genderRadioBtnFemale;
Button editBtn;
Button deleteBtn;
Intent intent;
DBHandler dbHandler;
public static final String USERID_EDITPROFILE = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
userName_editText = (EditText)findViewById(R.id.editprof_userName);
password_editText = (EditText)findViewById(R.id.editprof_password);
dob_editText = (EditText)findViewById(R.id.editprof_dob);
genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
editBtn = (Button)findViewById(R.id.editprof_editbtn);
deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
//new edit
genderRadioBtnMale = (RadioButton) findViewById(R.id.editprof_male_radio);
genderRadioBtnFemale = (RadioButton) findViewById(R.id.editprof_female_radio);
intent = getIntent();
dbHandler = new DBHandler(EditProfile.this);
setUserDetails();
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if(username == null){
Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(username);
if(users == null){
Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
}
else{
dbHandler.deleteInfo(username);
Intent redirectintent_home = new Intent(EditProfile.this,Home.class);
startActivity(redirectintent_home);
}
}
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
String username = userName_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
genderRadioBtn = (RadioButton)findViewById(selectedGender);
String gender = genderRadioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
users.setId(userID);
dbHandler.updateInfor(users);
Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
});
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if (username == null){
Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users_search = dbHandler.readAllInfor(username);
if(users_search == null){
Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
}
else{
userName_editText.setText(users_search.getUsername());
password_editText.setText(users_search.getPassword());
dob_editText.setText(users_search.getDob());
int id = users_search.getId();
Intent redirectintent = new Intent(EditProfile.this,EditProfile.class);
redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
startActivity(redirectintent);
}
}
}
});
}
public void setUserDetails(){
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
UserProfile.Users users = dbHandler.readAllInfor(userID);
userName_editText.setText(users.getUsername());
password_editText.setText(users.getPassword());
dob_editText.setText(users.getDob());
//new edit
String gender = users.getGender();
if(gender.equals("Male")){
genderRadioBtnMale.setChecked(true);
genderRadioBtnFemale.setChecked(false);
}
else{
genderRadioBtnMale.setChecked(false);
genderRadioBtnFemale.setChecked(true);
}
}
}
if you can try to check this also
ProfileManagement.java
package com.;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ProfileManagement extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup radioGroup;
RadioButton gender_radioBtn;
Button saveProfBtn;
public final static String USERID_PROFILEMGMT = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
username_editText = (EditText)findViewById(R.id.profmgmt_userName);
password_editText = (EditText)findViewById(R.id.profmgmt_password);
dob_editText = (EditText)findViewById(R.id.profmgmt_dob);
radioGroup = (RadioGroup)findViewById(R.id.profmgmt_radiogroup);
saveProfBtn = (Button)findViewById(R.id.profmgmt_btn);
final DBHandler dbHandler = new DBHandler(ProfileManagement.this);
saveProfBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = username_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = radioGroup.getCheckedRadioButtonId();
gender_radioBtn = (RadioButton)findViewById(selectedGender);
String gender = gender_radioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
boolean result = dbHandler.addInfo(users);
if(result == true){
Toast.makeText(ProfileManagement.this,"Successfully added",Toast.LENGTH_SHORT).show();
UserProfile.Users newusers = dbHandler.readAllInfor(username);
int userID = newusers.getId();
Intent intent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
intent.putExtra(USERID_PROFILEMGMT,Integer.toString(userID));
startActivity(intent);
}
}
});
}
}
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 COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "SURNAME"
;
public static final String COL4 = "MARKS";
​
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// SQLiteDatabase db = this.getWritableDatabase(); }
​
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, surname);
contentValues.put(COL4, marks);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAlldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
}
​
public boolean updateData(String id, String name, String surname, String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, id);
contentValues.put(COL2, name);
contentValues.put(COL3, surname);
contentValues.put(COL4, marks);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {
id
});
return true;
}
}
​
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ? ", new String[] {
id
});
}
​
public class MainActivity extends AppCompatActivity {
public Button but1;
​
DatabaseHelper myDb;
EditText editName, editSurname, editMarks, editTextid;
Button btnAddData;
Button btnViewall;
​
public void init() {
but1 = (Button) findViewById(R.id.button5);
but1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent my = new Intent(MainActivity.this, Activity2.class);
startActivity(my);
}
});
​
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myDb = new DatabaseHelper(this);
editName = (EditText) findViewById(R.id.editText_name);
editSurname = (EditText) findViewById((R.id.editText_surname));
editMarks = (EditText) findViewById((R.id.editText_marks));
editTextid = (EditText) findViewById(R.id.editText_id);
btnAddData = (Button) findViewById((R.id.button_add));
btnViewall = (Button) findViewById(R.id.button_view);
Adddata();
viewAll();
update();
}
public void Adddata() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString());
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data Not Inserted", Toast.LENGTH_LONG).show();
}
});
}
​
public void update() {
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextid.getText().toString(), editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString());
if (isUpdate == true)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Not Updated", Toast.LENGTH_LONG).show();
}
}
​
public void Delete() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDb.deleteData(editTextid.getText().toString());
if (deleteRows > 0)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
}
});
}
​
​
public void viewAll() {
btnViewall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAlldata();
if (res.getCount() == 0) {
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("id :" + res.getString(0) + "\n");
buffer.append("name :" + res.getString(1) + "\n");
buffer.append("surname: " + res.getString(2) + "\n");
buffer.append("marks: " + res.getString(3) + "\n\n");
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 COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "SURNAME"
; public static final String COL4 = "MARKS";
​
public DatabaseHelper( Context context) {
super(context, DATABASE_NAME , null, 1);
// SQLiteDatabase db = this.getWritableDatabase(); }
​
public void onCreate(SQLiteDatabase db) {
db.execSQL( " create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
onCreate(db);
}
public boolean insertData(String name, String surname, String marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2,name);
contentValues.put(COL3,surname);
contentValues.put(COL4,marks);
long result= db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAlldata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null );
return res; }
}
​
public boolean updateData(String id, String name, String surname, String marks){ SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1,id);
contentValues.put(COL2,name);
contentValues.put(COL3,surname);
contentValues.put(COL4,marks);
db.update(TABLE_NAME , contentValues, "ID = ?",new String[]{ id }); return true; } }
​
public Integer deleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME , "ID = ? ", new String[]{id}); }
​
public class MainActivity extends AppCompatActivity {
public Button but1;
​
DatabaseHelper myDb;
EditText editName, editSurname, editMarks,editTextid;
Button btnAddData;
Button btnViewall;
​
public void init(){
but1 = (Button)findViewById(R.id.button5);
but1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) { Intent my = new Intent(MainActivity.this,Activity2.class); startActivity(my); } } );
​
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById((R.id.editText_surname));
editMarks = (EditText)findViewById((R.id.editText_marks));
editTextid = (EditText)findViewById(R.id.editText_id);
btnAddData= (Button)findViewById((R.id.button_add));
btnViewall=(Button)findViewById(R.id.button_view);
Adddata();
viewAll();
update();
}
public void Adddata(){
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData( editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this ,"Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data Not Inserted", Toast.LENGTH_LONG).show(); } } ); }
​
public void update(){
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextid.getText().toString(), editName.getText().toString(), editSurname.getText().toString(), editMarks.getText().toString() );
if(isUpdate == true)
Toast.makeText(MainActivity.this , "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Not Updated" , Toast.LENGTH_LONG).show(); } }
​
public void Delete(){
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDb.deleteData(editTextid.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this , "Data Updated", Toast.LENGTH_LONG).show(); } } ); }
​
​
public void viewAll(){
btnViewall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= myDb.getAlldata();
if(res.getCount() == 0){
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("id :" + res.getString(0)+ "\n");
buffer.append("name :" + res.getString(1)+ "\n");
buffer.append("surname: " + res.getString(2) +"\n");
buffer.append("marks: " + res.getString(3) + "\n\n");
public final class UserProfile {
private UserProfile(){
}
public static UserProfile getProfile(){
UserProfile userProfile = new UserProfile();
return userProfile;
}
class Users implements BaseColumn{
public static final String TABLE_NAME = "UserInfo";
public static final String COL_ID = "_ID";
public static final String COL_USERNAME = "userName ";
public static final String COL_DOB = "dateOfBirth";
public static final String COL_GENDER = "Gender";
public static final String COL_PASSWORD = "Password";
private int id;
private String username;
private String dob;
private String gender;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public Users getUser(){
Users users = new Users();
return users;
}
}
seems this codeline works properly and there anrent any issues please implement it and check it..
well done

android database not open - SQLITE

I am trying to create password manager app that the user can manage her password in any websites.
The user need to fill 3 fields - Website, Username and Password.
Behind the scenes, the data should be insert to the database in SQLite but I think that the database not open, because I cant see the database folder in path: /data/data/MY_APP/
this is MySQLiteHelper: http://pastebin.com/4ZWJuS5W
package db_pkg;
import java.io.UTFDataFormatException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class MySQLiteHelper
{
public static final String DB_NAME = "mu_dbname";
public static final String TASKS_TABLE = "passwords";
public static final int DB_VER = 1;
public static final String TASK_ID = "_id";
public static final String TASK_WEB = "web";
public static final String TASK_USER = "user";
public static final String TASK_PASSWORD = "password";
// public static final String TASK_LAT = "lat";
// public static final String TASK_LNG = "lng";
private static final String SCRIPT_CREATE_DB = "create table "
+ TASKS_TABLE + "(" + BaseColumns._ID
+ " integer primary key autoincrement, " + TASK_WEB
+ " text not null, " + TASK_USER + " text not null, "
+ TASK_PASSWORD + " text not null" + ");";
private Context context;
private MyDBHelper myDBHelper;
public MySQLiteHelper(Context context)
{
this.context = context;
this.myDBHelper = new MyDBHelper(this.context);
}
public void addTaskItem(addPassword item)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_WEB, item.getWebsite());
values.put(TASK_USER, item.getUsername());
values.put(TASK_PASSWORD, item.getPassword());
database.insert(TASKS_TABLE, null, values);
database.close();
}
public boolean updateItemById(int taskID, addPassword item)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_WEB, item.getWebsite());
values.put(TASK_USER, item.getUsername());
values.put(TASK_PASSWORD, item.getPassword());
boolean b = database.update(TASKS_TABLE, values,
TASK_ID + "=" + taskID, null) > 0;
database.close();
return b;
}
public boolean deleteTaskItemById(int taskID)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
boolean b = database.delete(TASKS_TABLE, TASK_ID + "=" + taskID, null) > 0;
return b;
}
public Cursor getCursorALL()
{
Cursor cursor;
SQLiteDatabase database = myDBHelper.getReadableDatabase();
cursor = database.query(TASKS_TABLE,
new String[] { TASK_ID,TASK_WEB,TASK_USER,TASK_PASSWORD},
null,null, null, null, null);
return cursor;
}
//testing Debugging
public void printAllCursorDB()
{
Cursor cursor=getCursorALL();
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
StringBuffer st=new StringBuffer();
st.append("ID:"+cursor.getString(0));
st.append(" Text:"+cursor.getString(1));
st.append(" Phone:"+cursor.getString(2));
st.append(" Priority:"+cursor.getString(3));
Log.d("MyTasksDBMngr", st.toString());
cursor.moveToNext();
}
cursor.close();
}
private class MyDBHelper extends SQLiteOpenHelper
{
public MyDBHelper(Context context)
{
super(context, DB_NAME, null, DB_VER);
Log.i("MyDBHelper", "Constructor");
}
#Override
public void onCreate(SQLiteDatabase db)
{
String sqlst = String.format("drop table if exists %s;",
TASKS_TABLE);// משפט למחיקת הטבלה
db.execSQL(sqlst);
db.execSQL(SCRIPT_CREATE_DB);
Log.i("MyDBHelper", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onCreate(db);
}
}
}
this is addPassword:
http://pastebin.com/e17CQ6mF
package db_pkg;
public class addPassword {
String website, username, password;
int id;
public addPassword()
{
}
public addPassword(String website, String username, String password, int id) {
this.website = website;
this.username = username;
this.password = password;
this.id = id;
}
public addPassword(String website, String password, int id) {
this.website = website;
this.id = id;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWebsite() {
return website;
}
public void setWebsite(String web) {
if(web.length() < 2)
{
this.website = web;
}
}
public String getUsername() {
return username;
}
public void setUsername(String user) {
this.username = user;
}
public String getPassword() {
return password;
}
public void setPassword(String pass) {
this.password = pass;
}
}
this is my Activity:
package com.appweb.passwordmanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import db_pkg.MySQLiteHelper;
import db_pkg.addPassword;
public class newPassword extends AppCompatActivity {
private MySQLiteHelper niv;
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_password);
final EditText website = (EditText) findViewById(R.id.website);
final EditText username = (EditText) findViewById(R.id.username);
final EditText password = (EditText) findViewById(R.id.password);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isEmpty(password))
{
if(!isEmpty(website))
{
addPassword item = new addPassword(website.getText().toString(),
username.getText().toString(),
password.getText().toString(),
0);
niv.addTaskItem(item);
}
}
}
});
}
}
#Ramzi
SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.
At First Please read
Android SQLite Database
Android SQLite Database Tutorial
Example
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}

Categories