I have a list for that i want to add search function using search view. i have sqlite database and two fragments in which i am adding products and in another i am displaying the products in list view. i want to filter this list. how can i achieve this? i have searched many links but by searching all i have got confused..I am new to android so plz anyone can help? your help will be appretiated.. thnk u..
this is my main activity
public class MainActivity extends AppCompatActivity implements android.support.v7.widget.SearchView.OnQueryTextListener{
Toolbar mToolbar;
public DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
public DBHandler db;
ArrayList<Item> array_data;
public SearchView searchView;
ListView listview;
public ArrayAdapter<Item> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
array_data=new ArrayList<Item>();
db = new DBHandler(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
firstTimeFrag();
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(this,R.menu.menu_main);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
case R.id.search_view:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
private void firstTimeFrag(){
Fragment fr = new ViewStock();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.nav_contentframe, fr);
fragmentTransaction.commit();
}
}
this is my item class
public class Item {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id ,String item_name,String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name,String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> implements Filterable {
Context context;
// ValueFilter valueFilter;
ArrayList<Item> mStringFilterList;
ArrayList<Item> items;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
this.items=items;
mStringFilterList=items;
}
public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is my view stock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_view_stock, container, false);
MainActivity act = (MainActivity) this.getActivity();
act.listview = (ListView)rootview.findViewById(R.id.list);
act.listview.setTextFilterEnabled(true);
act.array_data = new ArrayList<Item>();
// Context mCtx = getActivity().getApplicationContext();
// ItemAdapter adapter = new ItemAdapter(getActivity(), R.layout.list_item, act.arrayList);
// listview.setAdapter(adapter);
act.db = new DBHandler(getActivity());
ArrayList<Item> item_array_from_db = act.db.Get_items();
for (int i = 0; i < item_array_from_db.size(); i++) {
int idno = item_array_from_db.get(i).getID();
String name = item_array_from_db.get(i).getItem_name();
String desc = item_array_from_db.get(i).getItem_desc();
String qty = item_array_from_db.get(i).getItem_qty();
Item cnt = new Item();
cnt.setID(idno);
cnt.setItem_name(name);
cnt.setItem_desc(desc);
cnt.setItem_qty(qty);
act.array_data.add(cnt);
}
act.db.close();
act.adapter = new ItemAdapter(getActivity(), R.layout.list_item,
act.array_data);
act.listview.setAdapter(act.adapter);
act.adapter.notifyDataSetChanged();
return rootview;
}
}
this is my database
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "stock";
private static final String TABLE_ITEMS = "items";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "itemname";
private static final String KEY_DESC = "itemdesc";
private static final String KEY_QTY = "itemqty";
private final ArrayList<Item> array_list = new ArrayList<Item>();
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT," + KEY_QTY + " INTEGER" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
onCreate(db);
}
public void Add_Item(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getItem_name());
values.put(KEY_DESC, item.getItem_desc());
values.put(KEY_QTY, item.getItem_qty());
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Item Get_Item(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC, KEY_QTY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
cursor.close();
db.close();
return item;
}
public ArrayList<Item> Get_items() {
try {
array_list.clear();
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setItem_name(cursor.getString(1));
item.setItem_desc(cursor.getString(2));
item.setItem_qty(cursor.getString(3));
array_list.add(item);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return array_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return array_list;
}
}
this is my view stock layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.owner.stock.ViewStock">
<!-- TODO: Update blank fragment layout -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:id="#+id/header"
android:weightSum="1"
android:background="#ff45f3ff">
<TextView
android:id="#+id/lbl_item_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/txt_item_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="#+id/lbl_item_desc"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/txt_item_desc"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="#+id/lbl_item_qty"
android:layout_width="100dp"
android:layout_height="match_parent"
android:text="#string/txt_item_qty"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="462dp"
android:id="#+id/list"
android:layout_gravity="center"
android:background="#android:color/background_light"
/>
</FrameLayout>
plz can anyone help me out for this?? I need to know can we use filter class for sqlite? and i have a fragment in that i have my list so how the search activity will be called??
You can use Filter instance from the ArrayAdapter to filter the items.
Your code can be like this-
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
mAdapter.getFilter().filter(mCurFilter);
and can be fired from the
public boolean onQueryTextChange(String newText)
Method of implemented SerachView.
For the detail you can have a look on the API Demo.
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Item> filterList = new ArrayList<Item>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ( (mStringFilterList.get(i).getItem_name())
.contains(constraint.toString())) {
Item item = new Item(mStringFilterList.get(i)
.getItem_name() , mStringFilterList.get(i)
.getItem_desc() , mStringFilterList.get(i)
.getItem_qty());
filterList.add(item);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
public void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<Item>) results.values;
notifyDataSetChanged();
}
}
this is my filter
Related
I have a Fragment with a RecyclerView. users input data and they will store in a SQLite DataBase. i am trying to Search in the items of this RecyclerView but it does not work,
here is my Fragment :
public class FragmentOne extends Fragment {
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private SearchView sv;
private ArrayList<Detail> mDetails=new ArrayList<>();
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView) view.findViewById(R.id.detail_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true); //This will reverse the data order but not scroll the RecyclerView to the last item
layoutManager.setStackFromEnd(true); //For keeping data order same and simply scrolling the RecyclerView to the last item
mDetailRecyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null) {
mNumberVisible =
savedInstanceState.getBoolean(SAVED_NUMBER_VISIBLE);
}
sv = (SearchView) view.findViewById(R.id.sv);
mAdapter = new DetailAdapter(mDetails);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit (String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
getDetailsSearch(query);
return false;
}
});
initViews();
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
..
..
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
// private TextView mDateTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate());
}
#Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent);
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
private Detail mDetail;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
#Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
#Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(final List<Detail> details) {
mDetails = details;
}
..
..
}
public void initViews(){
mDetailRecyclerView.setAdapter(mAdapter);
initSwipe();
}
..
..
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
DBAdapter db = new DBAdapter(getActivity());
db.openDB();
Detail p = null;
Cursor c = db.retrieve(searchTerm);
while (c.moveToNext()) {
String title = c.getString(2);
p = new Detail();
p.setTitle(title);
mDetails.add(p);
}
db.closeDB();
mDetailRecyclerView.setAdapter(mAdapter);
}
}
and this is my Database Adapter:
public class DBAdapter {
Context c;
SQLiteDatabase db;
DetailBaseHelper helper;
public DBAdapter (Context c) {
this.c = c;
helper = new DetailBaseHelper(c);
}
public void openDB() {
try {
db = helper.getWritableDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeDB() {
try {
helper.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Cursor retrieve (String searchTerm) {
String[] columns = {
"_id",
"uuid",
"title",
"des",
"date",
"rate"
Cursor c = null;
if (searchTerm != null && searchTerm.length()>0) {
String sql ="SELECT * FROM " +DetailDbSchema.DetailTable.NAME+
" WHERE "+DetailDbSchema.DetailTable.Cols.TITLE+
" LIKE '%"+searchTerm+"%'";
c = db.rawQuery(sql, null);
return c;
}
c = db.query(DetailDbSchema.DetailTable.NAME, columns,
null, null, null, null, null);
return c;
}
}
and here is DataBase Helper:
public class DetailBaseHelper extends SQLiteOpenHelper{
private static final int VERSION = 1;
private static final String DATABASE_NAME = "detailBase.db";
public DetailBaseHelper (Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL("create table " + DetailTable.NAME +
"(" +
" _id integer primary key autoincrement," +
DetailTable.Cols.UUID + ", " +
DetailTable.Cols.TITLE + ", " +
DetailTable.Cols.DES + ", " +
DetailTable.Cols.DATE + ", " +
DetailTable.Cols.RATE +
")"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,
int oldVersion, int newVersion) {
}
}
here is the tutorial that i used for this,
I'll be appreciate if u have any idea for helping me.
I think that the main problem is here you're changing the adapter, but the new adapter was never modified by the data of the results, and also you have to notify your recycler that the data set changed. so
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
/// the loop wiith the cursor
/// change the dataset
mAdapter = new DetailAdapter(mDetails);
mDetailRecyclerView.setAdapter(mAdapter);
/// tell the recycler there is a different data to display
mDetailRecyclerView.notifyDataSetChanged();
}
I'm new to Android programming, my problem is when update one record in another Activity from my MainActivity, the RecyclerView is not refreshed.
I have a ManinActivity with a RecyclerView, an activity_Detail for inserting and updating records and an activity_CardView to view the items stored in the database.
Here is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
rvNoteAdapter rvNoteAdapter;
private Toolbar mToolbar;
private FloatingActionButton fab;
private String rowID = null;
NoteDatabaseAdapter note_database;
FloatingActionButton btnAddNewRecord;
android.widget.LinearLayout parentLayout;
LinearLayout layoutDisplayPeople;
TextView tvNoRecordsFound;
ArrayList<create_note> notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAllWidgets();
note_database = new NoteDatabaseAdapter(MainActivity.this,6);
bindWidgetsWithEvent();
//displayAllRecords();
Recycler_do();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String note_type = data.getStringExtra(Constants.COLUMN_NOTE_TYPE);
String note_text = data.getStringExtra(Constants.COLUMN_NOTE_TEXT);
String note_id = data.getStringExtra(Constants.ID);
create_note note = new create_note();
note.setType(note_type);
note.setText(note_text);
if (requestCode == Constants.ADD_RECORD) {
//sQLiteHelper.insertRecord(firstname, lastname);
note_database.insert(note);
//recyclerAdapterNote.addItem(0,note);
} else if (requestCode == Constants.UPDATE_RECORD) {
note.setId(note_id);
//sQLiteHelper.updateRecord(firstname, lastname, rowID);
note_database.update(note);
}
Recycler_do();
}
}
private void getAllWidgets() {
btnAddNewRecord = (FloatingActionButton) findViewById(R.id.fab);
parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
layoutDisplayPeople = (LinearLayout) findViewById(R.id.layoutDisplayNote);
tvNoRecordsFound = (TextView) findViewById(R.id.tvNoRecordsFound);
recyclerView = (RecyclerView) findViewById(R.id.rvNotes);
}
public void Recycler_do ()
{
notes = note_database.getAllRecords();
LinearLayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
rvNoteAdapter adapter=new rvNoteAdapter(MainActivity.this,contacts);
recyclerView.setAdapter(adapter);
}
private void bindWidgetsWithEvent() {
btnAddNewRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddRecord();
}
});
}
private void onAddRecord() {
Intent intent = new Intent(MainActivity.this, Detail.class);
intent.putExtra(Constants.DML_TYPE, Constants.INSERT);
startActivityForResult(intent, Constants.ADD_RECORD);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
activity_Detail:
public class Detail extends AppCompatActivity {
EditText note_type;
EditText note_text;
RecyclerView recyclerView;
NoteDatabaseAdapter noteDatabaseAdapter=new NoteDatabaseAdapter(Detail.this,6);
String id;
String request="";
TextView toolbarText;
ImageView btnDML;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Detail);
getAllWidgets();
bindWidgetsWithEvent();
checkForRequest();
}
private void checkForRequest() {
request = getIntent().getExtras().get(Constants.DML_TYPE).toString();
if (request.equals(Constants.UPDATE)) {
toolbarText.setText("update");
note_text.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TEXT).toString());
note_type.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TYPE).toString());
id=getIntent().getExtras().get(Constants.ID).toString();
} else {
toolbarText.setText("new note");
}
}
private void bindWidgetsWithEvent() {
btnDML.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClick();
}
});
final ImageView back_btn = (ImageView) findViewById(R.id.back_btn);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Detail.this,"back btn",Toast.LENGTH_LONG).show();
finish(); //back to prev activity
}
});
}
private void getAllWidgets() {
note_type = (EditText) findViewById(R.id.note_type_EB);
note_text = (EditText) findViewById(R.id.note_text_EB);
toolbarText=(TextView) findViewById(R.id.toolbar_text);
btnDML = (ImageView) findViewById(R.id.save_btn);
recyclerView=(RecyclerView) findViewById(R.id.rvNotes);
setTitle(null);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
//topToolBar.setLogo(R.mipmap.ic_launcher);
// topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
}
private void onButtonClick() {
if (note_type.getText().toString().equals("") || note_text.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Add Both Fields", Toast.LENGTH_LONG).show();
} else if (request.equals(Constants.INSERT))
{
Intent intent = new Intent();
intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type.getText().toString());
intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text.getText().toString());
intent.putExtra(Constants.ID, id);
setResult(RESULT_OK, intent);
finish();
}
else if (request.equals(Constants.UPDATE))
{
create_note note = new create_note();
note.setType(note_type.getText().toString());
note.setText(note_text.getText().toString());
note.setId(id);
try {
noteDatabaseAdapter.update(note);
ArrayList<create_note> noteArrayList = noteDatabaseAdapter.getAllRecords();
ArrayList<create_note> temp=noteDatabaseAdapter.getAllRecords();
rvNoteAdapter rvNoteAdaptermodel=new rvNoteAdapter(Detail.this,temp);
**//do not refresh RecyclerView
rvNoteAdaptermodel.updateItems(noteArrayList);**
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
finish();
//
}
}
activity_CardView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:padding="5dp"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv">
<RelativeLayout
android:id="#+id/inflateParentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
>
<ImageView
android:contentDescription="#string/action_new"
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:src="#mipmap/ic_save"
/>
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_type_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
/>
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_text_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:layout_below="#+id/note_type_inflate" />
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_id_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:layout_below="#+id/note_text_inflate" />
</RelativeLayout>
rvNoteAdapter.java (Adapter for RecyclerView)
public class rvNoteAdapter extends RecyclerView.Adapter<rvNoteAdapter.ViewHolder> {
private List<create_note> noteList= Collections.emptyList();
Context noteContext;
private create_note note;
private String rowID = null;
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView noteText;
public TextView noteType;
public TextView noteId;
private CardView cardView;
public ViewHolder(View itemView){
super(itemView);
noteText=(TextView) itemView.findViewById(R.id.note_text_inflate);
noteType=(TextView) itemView.findViewById(R.id.note_type_inflate);
noteId=(TextView) itemView.findViewById(R.id.note_id_inflate);
cardView = (CardView) itemView.findViewById(R.id.cv);
}
}
public rvNoteAdapter(Context context,List<create_note> Note_List){
this.noteList=Note_List;
this.noteContext=context;
}
private Context getNoteContext()
{
return noteContext;
}
#Override
public rvNoteAdapter.ViewHolder onCreateViewHolder (ViewGroup parent,int viewType)
{
// Context context=parent.getContext();
// LayoutInflater inflater=LayoutInflater.from(context);
//View NoteView=inflater.inflate(R.layout.activity_CardView,parent,false);
//ViewHolder viewHolder=new ViewHolder(NoteView);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_CardView, parent, false);
ViewHolder memberViewHolder = new ViewHolder(view);
return memberViewHolder;
}
#Override
public void onBindViewHolder(final rvNoteAdapter.ViewHolder viewHolder,int position)
{
//viewHolder.noteText.setText(noteList.get(position).getText());
create_note note=noteList.get(position);
viewHolder.noteText.setText(note.getText());
viewHolder.noteType.setText(note.getType());
viewHolder.noteId.setText(note.getId());
final int pos=position;
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
create_note note=(create_note)v.getTag();
String note_text=viewHolder.noteText.getText().toString();
String note_type=viewHolder.noteType.getText().toString();
String note_id=viewHolder.noteId.getText().toString();
Intent intent = new Intent(v.getContext(), Detail.class);
intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type);
intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text);
intent.putExtra(Constants.ID, note_id);
intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);
v.getContext().startActivity(intent);
// mainActivity.onUpdateRecord(note_text,"jhkhkj",note_id);
Toast.makeText(noteContext,"clicked"+pos,Toast.LENGTH_LONG).show();
}
});
}
//my problem with this code that not refreshed RecyclerView
public void updateItems(ArrayList<create_note> notes)
{
noteList.clear();
noteList.addAll(notes);
notifyDataSetChanged();
}
public void addItem(int position, create_note note) {
try {
noteList.add(position, note);
notifyItemInserted(position);
}
catch (Exception e) {
}
}
public void removeItem(create_note note) {
int position=noteList.indexOf(note);
noteList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return noteList.size();
}
NoteDatabaseAdapter.java (adapter for database) :
public class NoteDatabaseAdapter extends SQLiteOpenHelper {
public static final String TABLE_NAME = "tbl_note";
public static final String ID = "ID";
public static final String COLUMN_NOTE_TYPE = "type";
public static final String COLUMN_NOTE_TEXT = "text";
private SQLiteDatabase database;
public NoteDatabaseAdapter(Context context,int newVersion) {
super(context,"noteDatabase.db",null,newVersion);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
String sql = "create table "+ TABLE_NAME + " ( id integer primary key autoincrement NOT NULL," + COLUMN_NOTE_TYPE + " NVARCHAR," + COLUMN_NOTE_TEXT + " NVARCHAR)";
db.execSQL(sql);
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
try{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
}
public void insert(create_note note) {
try {
database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NOTE_TYPE, note.getType());
contentValues.put(COLUMN_NOTE_TEXT, note.getText());
database.insert(TABLE_NAME, null, contentValues);
database.close();
} catch (Exception e) {
Log.d("Database", "Exception:" + e.getMessage());
}
}
public void update(create_note note) {
try {
database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NOTE_TYPE, note.getType());
contentValues.put(COLUMN_NOTE_TEXT, note.getText());
database.update(TABLE_NAME,contentValues,"id="+note.getId(),null);
database.close();
} catch (Exception e) {
Log.d("Database", "Exception:" + e.getMessage());
}
}
public ArrayList<create_note> getAllRecords() {
database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);
ArrayList<create_note> notes = new ArrayList<create_note>();
create_note note_model;
cursor.moveToLast();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
note_model = new create_note();
note_model.setId( cursor.getString(0));
note_model.setType(cursor.getString(1));
note_model.setText(cursor.getString(2));
notes.add(note_model);
cursor.moveToPrevious();
}
}
cursor.close();
database.close();
return notes;
}
}
create_note.java (object class)
public class create_note {
private String id;
private String type;
private String text;
public create_note(){}
public create_note(String type, String text) {
this.type = type;
this.text = text;
}
public create_note(String id, String type, String text) {
this.id = id;
this.type = type;
this.text = text;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setType(String type) {
this.type = type;
}
}
My problem is in rvNoteAdapter.java on UpdateItem method.
adapter.invalidate is not working,
Can anybody help me?
Use this to set and refresh apter of recyclerview.
if (null == rvNoteAdapter) {
rvNoteAdapter rvNoteAdaptermodel=new
rvNoteAdapter(Detail.this,temp);
rvNoteAdaptermodel.updateItems(noteArrayList);
recyclerView.setAdapter(adapter);
} else {
rvNoteAdaptermodel.updateItems(noteArrayList);
rvNoteAdapter.notifyDataSetChanged();
}
And your updateItemsmethod should be like,
public void updateItems(ArrayList<create_note> notes)
{
noteList.clear();
noteList.addAll(notes);
}
i use this method to update Recyclerview
in MainActivity
set notes ArreyList as static
set rvNotAdapter as static
then i use this variables in DetailActivity.
in DetailActivity use this code :
ArreyList<create_note> noteArreyList = noteDatabaseAdapter.getAllRecords();
MainActivity.notes.clear();
MainActivity.notes.addAll(noteArreyList);
MainActivity.rvNoteAdapter.notifyDataSetChanged();
i use this codes after i updete my data in database :
noteDatabaseAdapter.update(note);
MultiAutoCompleteTextView Custom adapter, How to dismissDropDown
my code click listener is not working.
output image
Fragment
public class ShareDialogFragment extends DialogFragment implements View.OnClickListener{
Dialog dialog;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String articleID;
MultiAutoCompleteTextView myMultiAutoCompleteTextView;
TextView Cancel, share;
Context context;
public static ShareDialogFragment fragment;
OnClickListenerCustom onClickListenerCustom;
private PrefManager pref;
ArrayList<ShareWithArticle> userList = new ArrayList<>();
MultiAutoCompleteAdapter adapter;
RequestParse requestParse;
public ShareDialogFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.alert_dialog);
Bundle arg = getArguments();
if(arg!=null){
articleID = getArguments().getString("ArticleId");
}
dialog = new Dialog(getActivity());
requestParse = new RequestParse();
UserNameTo();
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
context = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_share_dialog, container, false);
Cancel = (TextView)view.findViewById(R.id.Cancel);
Cancel.setOnClickListener(this);
share = (TextView) view.findViewById(R.id.textView22);
myMultiAutoCompleteTextView = (MultiAutoCompleteTextView)view.findViewById(R.id.editText);
//ShareWithArticle s = (ShareWithArticle) myMultiAutoCompleteTextView.getAdapter().getItem(position);
return view;
}
public void UserNameTo(){
requestParse.postJson(ConfigApi.UserToArticle(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
userList = ShareArticleuserNameTo.parseResponse(result);
adapter = new MultiAutoCompleteAdapter(context,R.layout.custom_dropdown, userList);
myMultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
myMultiAutoCompleteTextView.setAdapter(adapter);
myMultiAutoCompleteTextView.dismissDropDown();
}
#Override
public void onRequestError(String errorMessage) {
M.i("============errorMessage", errorMessage);
}
#Override
public Map OnParam(Map<String, String> params) {
return null;
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Cancel:
getDialog().dismiss();
break;
}
}
}
and My Custom Adapter MultiAutoCompleteTextView Code:
public class MultiAutoCompleteAdapter extends ArrayAdapter<ShareWithArticle> {
//ShareWithArticle
private final Context mContext;
private final List<ShareWithArticle> mDepartments;
private final List<ShareWithArticle> mDepartments_All;
private final List<ShareWithArticle> mDepartments_Suggestion;
private final int mLayoutResourceId;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
public MultiAutoCompleteAdapter(Context context, int resource, List<ShareWithArticle> departments) {
super(context, resource, departments);
this.mContext = context;
this.mLayoutResourceId = resource;
this.mDepartments = new ArrayList<>(departments);
this.mDepartments_All = new ArrayList<>(departments);
this.mDepartments_Suggestion = new ArrayList<>();
}
public int getCount() {
return mDepartments.size();
}
public ShareWithArticle getItem(int position) {
return mDepartments.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
ShareWithArticle department = getItem(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
ImageView userProfile = (ImageView) convertView.findViewById(R.id.profileImages);
name.setText(department.getUsrFNm() + " " + department.getUsrLNm());
volleySingleton = VolleySingleton.getInstance();
imageLoader = volleySingleton.getImageLoader();
requestQueue = volleySingleton.getRequestQueue();
String UsrPrf = department.getUsrPicture();
RequestParse.loadImages(UsrPrf, userProfile);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
/*#Override
public boolean isEnabled(int position) {
return position % 2 == 0 ? false : true;
}*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
public String convertResultToString(Object resultValue) {
return ((ShareWithArticle) resultValue).getUsrFNm()+ " " + ((ShareWithArticle) resultValue).getUsrLNm();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
mDepartments_Suggestion.clear();
for (ShareWithArticle department : mDepartments_All) {
if (department.getUsrFNm().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
mDepartments_Suggestion.add(department);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = mDepartments_Suggestion;
filterResults.count = mDepartments_Suggestion.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mDepartments.clear();
if (results != null && results.count > 0) {
// avoids unchecked cast warning when using mDepartments.addAll((ArrayList<Department>) results.values);
List<?> result = (List<?>) results.values;
for (Object object : result) {
if (object instanceof ShareWithArticle) {
mDepartments.add((ShareWithArticle) object);
}
}
} else if (constraint == null) {
// no filter, add entire original list back in
mDepartments.addAll(mDepartments_All);
}
notifyDataSetChanged();
}
};
}
}
I have used this solution to filter my RecyclerView. Using the solution I was able to get the result while typing. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
This is how my result looks like.
https://imgur.com/nwyetEd
This is my Adapter
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private LayoutInflater inflater;
private ContactViewHolder viewHolder;
private ArrayList<Contact> contactsList = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
boolean fromMyContacts;
Context context;
public ContactsAdapter(Context context, boolean fromMyContacts){
inflater = LayoutInflater.from(context);
this.context = context;
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
this.fromMyContacts = fromMyContacts;
}
public void setContactsList(ArrayList<Contact> contactsList){
this.contactsList = contactsList;
notifyItemRangeChanged(0, contactsList.size());
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.contact_list, parent, false);
viewHolder = new ContactViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact current = contactsList.get(position);
viewHolder.name.setText(current.name);
viewHolder.phone.setText(current.phone);
viewHolder.city.setText(current.location + ", " + current.city);
if(fromMyContacts) {
if (current.verified) {
viewHolder.verified.setImageResource(R.drawable.ic_check_circle);
} else {
viewHolder.verified.setImageResource(R.drawable.ic_cancel);
}
}
String image_url = current.image_url;
if(!image_url.equals("null")){
Picasso.with(context).load(image_url).into(viewHolder.contactIcon);
}else{
viewHolder.contactIcon.setImageResource(R.drawable.contact_icon);
}
}
#Override
public int getItemCount() {
return contactsList.size();
}
public Contact removeItem(int position){
final Contact contacts = contactsList.remove(position);
notifyItemRemoved(position);
return contacts;
}
public void addItem(int position, Contact contactList){
contactsList.add(position, contactList);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition){
final Contact contacts = contactsList.remove(fromPosition);
contactsList.add(toPosition, contacts);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(List<Contact> contacts){
applyAndAnimateRemovals(contacts);
applyAndAnimateAdditions(contacts);
applyAndAnimateMovedItems(contacts);
}
private void applyAndAnimateRemovals(List<Contact> newModels) {
for (int i = contactsList.size() - 1; i >= 0; i--) {
final Contact model = contactsList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Contact> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Contact model = newModels.get(i);
if (!contactsList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<Contact> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Contact model = newModels.get(toPosition);
final int fromPosition = contactsList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
}
And this is my Model
public class Contact {
String name;
String phone;
String city;
String location;
Boolean verified;
String image_url;
public Contact(String name, String phone, String city, String location, Boolean verified, String image_url){
this.name = name;
this.phone = phone;
this.city = city;
this.location = location;
this.verified = verified;
this.image_url = image_url;
}
}
This is the Activity where I use my filter
public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener, SearchView.OnQueryTextListener {
private RecyclerView recyclerView;
private ContactsAdapter adapter;
private NetworkChecker networkChecker;
private SessionManager sessionManager;
private AppConfig appConfig;
private RelativeLayout loading, retry;
private Button tryAgain;
AlertHelper alertHelper;
final ArrayList<Contact> contactArrayList = new ArrayList<>();
String url;
DebugHelper debugHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
debugHelper = new DebugHelper();
loading = (RelativeLayout) findViewById(R.id.loadingPanel);
retry = (RelativeLayout) findViewById(R.id.retry);
tryAgain = (Button) findViewById(R.id.tryAgainButton);
tryAgain.setOnClickListener(this);
alertHelper = new AlertHelper(this);
networkChecker = new NetworkChecker(this);
sessionManager = new SessionManager(this);
appConfig = new AppConfig();
String phone = sessionManager.getLoggedInUserPhone();
url = appConfig.getApiUrlForSpecificContacts(phone);
recyclerView = (RecyclerView) findViewById(R.id.contactsView);
adapter = new ContactsAdapter(getApplicationContext(), true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
sendJsonRequest(url);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView phone = (TextView) view.findViewById(R.id.contact_phone);
TextView name = (TextView) view.findViewById(R.id.contact_name);
Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
i.putExtra("selected_user_phone", phone.getText());
i.putExtra("selected_user_name", name.getText());
startActivity(i);
}
})
);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddContactActivity.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void sendJsonRequest(String url) {
if (networkChecker.networkAvailable()) {
loading.setVisibility(View.VISIBLE);
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("contact_info");
if(jsonArray != null){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentContact = jsonArray.getJSONObject(i);
String name = currentContact.getString("name");
String phone = currentContact.getString("phone");
String city = currentContact.getString("city");
String address = currentContact.getString("address");
Boolean verified = currentContact.getBoolean("verified");
String image_url = currentContact.getString("image_url");
Contact contact = new Contact(name, phone, city, address, verified, image_url);
contactArrayList.add(contact);
}
adapter.setContactsList(contactArrayList);
}
else{
alertHelper.displayDialog("No Contacts Found.");
}
}catch (Exception e){
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
alertHelper.displayDialog(getString(R.string.connection_failed));
} else {
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
});
requestQueue.add(stringRequest);
} else {
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list_menu, menu);
debugHelper.L("Search Click Vayo");
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tryAgainButton:
sendJsonRequest(url);
break;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<Contact> filteredModelList = filter(contactArrayList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactArrayList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
Can anyone help me please?
assuming contactsList is var with the full contacts
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactsList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
He has defined in this way:
public void setModels(List<ExampleModel> models) {
mModels = new ArrayList<>(models);
}
Initialize like the way he has done.
Your soultion would be:
this.contactsList = new ArrayList<>(contactsList);
You need to move your filter() method from your Activity to your Adapter. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList and copyOfContactsList variables.
Change your Adapter's constructor as follows:
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
....
private ArrayList<Contact> contactsList = new ArrayList<>();
private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
....
public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
...
this.contactsList = dataSet;
copyOfContactsList.addAll(dataSet);
...
}
and this is the filter method to be added to your Adapter:
public void filter(String text) {
if(text.isEmpty()){
contactsList.clear();
contactsList.addAll(copyOfContactsList);
} else{
ArrayList<Contact> result = new ArrayList<>();
text = text.toLowerCase();
for(Contact item: copyOfContactsList){
if(item.getName().toLowerCase().contains(text)){
result.add(item);
}
}
contactsList.clear();
contactsList.addAll(result);
}
notifyDataSetChanged();
}
hey guys currently Im studying recyclerview and sqlite on how to fetch data from sqlite then show it to recyclerview. I made it working but Im not confident that it is the right way. here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar mToolBar;
private NavigationView mDrawer;
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mDrawerLayout;
private Button alarmButton;
private AlarmManager alarmManager;
private PendingIntent sender;
private RecyclerView listReminder;
private RemindersAdapter adapter;
List<ListInfo> data;
ListInfo infoData;
Button addReminderBtn;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDrawer();
initView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mdrawerToggle.onConfigurationChanged(newConfig);
}
public void initDrawer(){
mToolBar = (Toolbar) findViewById(R.id.app_bar);
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
setSupportActionBar(mToolBar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolBar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.setDrawerListener(mdrawerToggle);
// indicator based on whether the drawerlayout is in open or closed
mdrawerToggle.syncState();
}
public void initView(){
listReminder = (RecyclerView) findViewById(R.id.listData);
dbHandler = new MyDBHandler(this);
adapter = new RemindersAdapter(this, dbHandler.getAllData_a());
listReminder.setAdapter(adapter);
listReminder.setLayoutManager(new LinearLayoutManager(this));
addReminderBtn = (Button) findViewById(R.id.addBtn);
addReminderBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addBtn:
Intent addReminder = new Intent(this, AddReminderActivity.class);
startActivity(addReminder);
break;
}
}
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_NAME = "paroah.db";
public static final String TABLE_REMINDER = "reminders";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE_REMINDER = "title";
public static final String COLUMN_DESC_REMINDER = "desc";
public static final String COLUMN_DATE_REMINDER = "date_created";
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE "
+TABLE_REMINDER+ "(" +
COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_TITLE_REMINDER + " TEXT ,"+
COLUMN_DESC_REMINDER + " TEXT ,"+
COLUMN_DATE_REMINDER + " TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("DROP TABLE IF EXIST " + TABLE_REMINDER); // onCreate(db);
Log.d("aoi", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
try {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_REMINDER);
onCreate(db);
} catch (SQLException e) {
Log.d("aoi", "getting exception "
+ e.getLocalizedMessage().toString());
}
}
public void addReminder(ListInfo reminder ){
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE_REMINDER, reminder.getTitle());
values.put(COLUMN_DESC_REMINDER, reminder.getDesc());
values.put(COLUMN_DATE_REMINDER, reminder.getDate());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_REMINDER, null, values);
db.close();
}
public void printDatabase(){
SQLiteDatabase db = getWritableDatabase();
}
public List<ListInfo> getAllData_a(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+TABLE_REMINDER;
Cursor cursor=db.rawQuery(query, null);
List<ListInfo> data=new ArrayList<>();
while (cursor.moveToNext()){
int _id=cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(COLUMN_DATE_REMINDER));
ListInfo current = new ListInfo();
current.set_id(_id);
current.title = title;
current.desc = desc;
current.date = date;
data.add(current);
}
return data;
}
}
RemindersAdapter.java
public class RemindersAdapter extends RecyclerView.Adapter<RemindersAdapter.ItemViewHolder> {
private final LayoutInflater inflater;
List<ListInfo> data = Collections.emptyList();
public RemindersAdapter(Context context, List<ListInfo> data){
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.reminder_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
ListInfo current = data.get(position);
holder.title.setText(current.title);
}
#Override
public int getItemCount() {
return data.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder{
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
}
}
}
is there any other way to make this code clean? What I need are the concepts and examples if you do have, or what I need to learn to make it clean. TIA!!