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.
Related
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.
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
I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
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;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???
When I run the program, everything looks fine but the moment I type a letter in the search bar, the program crashes immediately.It mostly shows Exceptions at searchBar() function in LibraryDbAdapter class and at onQueryTextChange(String newText) in SearchViewActivity class.I am using ListView too.
LibraryDbAdapter.java
package com.example.waheed.library;
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.util.Log;
/**
* Created by Waheed on 6/30/17.
*/
public class LibraryDbAdapter {
public static final String KEY_ROWID = "rowid";
//public static final String KEY_LIBRARY = "library";
public static final String KEY_BOOKNAME = "bookname";
public static final String KEY_BOOKAUTHOR = "bookauthor";
public static final String KEY_STORENAME = "storename";
public static final String KEY_STOREADDRESS = "storeaddress";
public static final String KEY_STORELAT = "storelat";
public static final String KEY_STORELONG = "storelong";
public static final String KEY_SEARCH = "searchData";
private static final String TAG = "LibraryDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryData";
private static final String FTS_VIRTUAL_TABLE = "LibraryInfo";
private static final int DATABASE_VERSION = 1;
//Create a FTS3 Virtual Table for fast searches
private static final String DATABASE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
// KEY_LIBRARY + "," +
KEY_BOOKNAME + "," +
KEY_BOOKAUTHOR + "," +
KEY_STORENAME + "," +
KEY_STOREADDRESS + "," +
KEY_STORELAT + "," +
KEY_STORELONG + "," +
KEY_SEARCH + "," +
" UNIQUE (" + KEY_BOOKNAME + "));";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
public LibraryDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public LibraryDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createLibrary( String bookname, String bookauthor, String storename, String storeaddress, String storelat, String storelong) {
ContentValues initialValues = new ContentValues();
String searchValue = bookname;
//initialValues.put(KEY_LIBRARY, library);
initialValues.put(KEY_BOOKNAME, bookname);
initialValues.put(KEY_BOOKAUTHOR, bookauthor);
initialValues.put(KEY_STORENAME, storename);
initialValues.put(KEY_STOREADDRESS, storeaddress);
initialValues.put(KEY_STORELAT, storelat);
initialValues.put(KEY_STORELONG, storelong);
initialValues.put(KEY_SEARCH, searchValue);
return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
public Cursor searchBook(String inputText) throws SQLException {
Log.w(TAG, inputText);
String query = "SELECT " +
KEY_BOOKNAME +
" from " + FTS_VIRTUAL_TABLE +
" where " + KEY_SEARCH + " MATCH '" + inputText + "';";
Log.w(TAG, query);
Cursor mCursor = mDb.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean deleteAllLibrary() {
int doneDelete = 0;
doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null, null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
SearchViewActivity.java
package com.example.waheed.library;
import java.util.Calendar;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements
SearchView.OnQueryTextListener,
SearchView.OnCloseListener {
private ListView mListView;
private SearchView searchView;
private LibraryDbAdapter mDbHelper;
private TextView inspectionDate;
private TextView bookName;
private TextView bookAuthor;
private TextView storeName;
private TextView storeAddress;
private TextView storeLat;
private TextView storeLong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchView = (SearchView) findViewById(R.id.search);
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
mListView = (ListView) findViewById(R.id.list);
inspectionDate = (TextView) findViewById(R.id.inspectionDate);
displayDate();
mDbHelper = new LibraryDbAdapter(this);
mDbHelper.open();
//Clean all Customers
mDbHelper.deleteAllLibrary();
//Add some Customer data as a sample
mDbHelper.createLibrary("How to Win Friends and Influence People", "Dale Carnegie", "Book Centre", " Haider Rd, Rawalpindi 46000", "33.596651", "73.049094");
mDbHelper.createLibrary("The 7 Habits of Highly Effective People", "Stephen Covey", "Idris Book Bank", "Bank Rd, Rawalpindi 46000", "33.595789", "73.052405");
mDbHelper.createLibrary("Think and Grow Rich", "Napoleon Hill", "Students Book Company", "Bank Rd, Rawalpindi 44000", "33.596524", "73.051051");
mDbHelper.createLibrary("Psycho-Cybernetics", "Maxwell Maltz", "Old Book Bank", "Green Super Market, Kashmir Rd, Saddar, Rawalpindi, Punjab", "33.595810", "73.051530");
mDbHelper.createLibrary("How to stop worrying and start living", "Dale Carnegie", "Saeed Book Bank", "F-, Street 7, Islamabad 44000", "33.722446", "73.058763");
mDbHelper.createLibrary("A New Earth", " Eckhart Tolle", "Variety Books", "41-BC, Bank Rd, Saddar, Rawalpindi 46000", "33.597497", "73.049917");
mDbHelper.createLibrary("Blink: The Power of Thinking Without Thinking", "Malcolm Gladwell", "Rehan Book Shop", "Islamabad", "33.689734", "73.031652");
mDbHelper.createLibrary("First Things First", "Stephen Covey", "Idris Book Bank", "Bank Rd, Rawalpindi 46000", "33.595789", "73.052405");
mDbHelper.createLibrary("Emotional Intelligence", "Daniel Goleman", "Book Centre", " Haider Rd, Rawalpindi 46000", "33.596651", "73.049094");
mDbHelper.createLibrary("Anatomy of the Spirit", "Caroline Myss", "Students Book Company", "Bank Rd, Rawalpindi 44000", "33.596524", "73.051051");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mDbHelper != null) {
mDbHelper.close();
}
}
public boolean onQueryTextChange(String newText) {
showResults(newText + "*");
return false;
}
public boolean onQueryTextSubmit(String query) {
showResults(query + "*");
return false;
}
public boolean onClose() {
showResults("");
return false;
}
private void showResults(String query) {
Cursor cursor = mDbHelper.searchBook((query != null ? query.toString() : "####"));
if (cursor == null) {
//
} else {
// Specify the columns we want to display in the result
String[] from = new String[]{
LibraryDbAdapter.KEY_BOOKNAME,
LibraryDbAdapter.KEY_BOOKAUTHOR,
LibraryDbAdapter.KEY_STORENAME,
LibraryDbAdapter.KEY_STOREADDRESS,
LibraryDbAdapter.KEY_STORELAT,
LibraryDbAdapter.KEY_STORELONG
};
// Specify the Corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.sbook,
R.id.sauthor,
R.id.sstore,
R.id.sstoreaddress,
R.id.slat,
R.id.slong};
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter books = new SimpleCursorAdapter(this,R.layout.bookresult, cursor, from, to);
mListView.setAdapter(books);
// Define the on-click listener for the list items
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) mListView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String Book = cursor.getString(cursor.getColumnIndexOrThrow("Book"));
String Author = cursor.getString(cursor.getColumnIndexOrThrow("Author"));
String Store = cursor.getString(cursor.getColumnIndexOrThrow("Store"));
String storeaddress = cursor.getString(cursor.getColumnIndexOrThrow("storeaddress"));
String lat = cursor.getString(cursor.getColumnIndexOrThrow("lat"));
String lon = cursor.getString(cursor.getColumnIndexOrThrow("lon"));
//Check if the Layout already exists
LinearLayout bookLayout = (LinearLayout)findViewById(R.id.booklayout);
if(bookLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View bookInfo = getLayoutInflater().inflate(R.layout.bookinfo, leftLayout, false);
leftLayout.addView(bookInfo);
}
//Get References to the TextViews
bookName = (TextView) findViewById(R.id.book);
bookAuthor = (TextView) findViewById(R.id.author);
storeName = (TextView) findViewById(R.id.store);
storeAddress = (TextView) findViewById(R.id.storeaddress);
storeLat = (TextView) findViewById(R.id.latitude);
storeLong = (TextView) findViewById(R.id.longitude);
// Update the parent class's TextView
bookName.setText(Book);
bookAuthor.setText(Author);
storeName.setText(Store);
storeAddress.setText(storeaddress);
storeLat.setText(lat);
storeLong.setText(lon);
searchView.setQuery("",true);
}
});
}
}
private void displayDate() {
final Calendar c = Calendar.getInstance();
inspectionDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(c.get(Calendar.MONTH) + 1).append("/")
.append(c.get(Calendar.DAY_OF_MONTH)).append("/")
.append(c.get(Calendar.YEAR)).append(" "));
}
}
Below is my database that I have already created and it works fine, it can save the data to the database,I am really new to this android project and need guidance on how to display all data that was saved inside the listview.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BmiDatabase {
private data helper;
private SQLiteDatabase help;
private Context context;
public BmiDatabase(Context context){
helper = new data(context);
help = helper.getWritableDatabase();
this.context=context;
}
public long insertData(String bmi, String status, String weight){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(data.NAME, bmi);
contentValues.put(data._STATUS, status);
contentValues.put(data.WEIGHT, weight);
long id = db.insert(data.DATABASE_TABLE, null, contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {data.UID, data.NAME, data._STATUS, data.WEIGHT};
Cursor cursor = db.query(data.DATABASE_TABLE, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext())
{
// int index1 = cursor.getColumnIndex(data.UID);
// int cid = cursor.getInt(index1);
int cid = cursor.getInt(0);
String bmi = cursor.getString(1);
String status = cursor.getString(2);
String weight = cursor.getString(3);
buffer.append(cid +" "+bmi+" kg "+status+" "+weight+ "\n");
}
return buffer.toString();
}
public static class data extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME = "bmidatabase";
private static final String DATABASE_TABLE = "bmitable";
private static final int DB_VERSION = 7;
public static final String UID = "_id";
public static final String NAME = "Bmi";
public static final String _STATUS = "Status";
public static final String WEIGHT = "Weight";
private static final String DROP_TABLE= "DROP TABLE IF EXISTS "+DATABASE_TABLE;
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +
" "+NAME+" VARCHAR(255)," +
" "+_STATUS+" VARCHAR(255)," +
""+WEIGHT+" VARCHAR(255));";
public data(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
this.context=context;
}
public void getAllData(){
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Message.message(context,"Database Created");
}
catch (SQLException e){
Message.message(context, "Failed" +e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
Message.message(context, "DATABASE DELETED");
db.execSQL(DROP_TABLE);
onCreate(db);
}
catch(SQLException e){
Message.message(context, "SQL FAILED");
}
}
}
}
Below is the code for my mainactivity, it shows that I can display it using a toast, but I have no idea how to call the method to populate the list view with those data.
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static DataHelper DataHelper;
//DataHelper helper = new DataHelper(this);
private static BmiDatabase data;
private EditText weightinputid;
private EditText heightinputid;
private Button buttonBMI, save, detail;
private TextView BMIStatus;
private TextView BMIfinal;
private double weight =0.0;
private double height =0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupDB();
// setDB();
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
data = new BmiDatabase(this);
}
public void calculateBMI (View v){
String status;
weight= Double.parseDouble(weightinputid.getText().toString());
height= Double.parseDouble(heightinputid.getText().toString());
double bmi = weight/(height/100*height/100);
String result = String.format("%.2f", bmi);
Log.d("MainActivity", result);
BMIfinal.setText(result, TextView.BufferType.NORMAL);
if(bmi < 16){
status = "Seriously Underweight";
}
else if(bmi >=16.0 && bmi < 18.0){
status = "Underweight";
}
else if(bmi >=18.0 && bmi <24.0){
status = "Normal";
}
else{
status = "Obese";
}
BMIStatus.setText(status);
}
public void save(View v){
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String weight = weightinputid.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0)
{
Message.message(this, "");
}
else
{
Message.message(this, "");
}
}
public void detail(View v){
String d = data.getAllData();
Message.message(this, d);
}
}