Cannot add List to custom list view. im having trouble with String[] , i was trying to get my users from firebase database and stores it to my
private ArrayList<UserInfo> userInfos;
userInfos=new ArrayList<>();
but when running it to emulator my listview is showing blank,i've tried checking the List<String> friends = new ArrayList<>(); and my users are available., Could anyone please help me with this?
My MainActivityCustonlistViewnew.java
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
public class MainActivityCustonlistViewnew extends AppCompatActivity {
private ArrayList<UserInfo> userInfos;
private CustomListAdapter customListAdapter;
private ListView customListView;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference databaseReference = firebaseDatabase.getReference();
private DatabaseReference UserData = databaseReference.child("Users");
private List<String> friends = new ArrayList<>();
private String[] names ;
private String[] professions={
"Rank 1",
"Rank 2",
"Rank 3"
};
private int[] photos={
R.drawable.sample_5,
R.drawable.sample_1,
R.drawable.sample_6
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maincustomlistview);
setSupportActionBar((Toolbar)findViewById(R.id.toolbar));
// ArrayList arrayList = new ArrayList(friends);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String friend = ds.getKey();
friends.add(friend);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
UserData.addListenerForSingleValueEvent(eventListener);
customListView=(ListView)findViewById(R.id.custom_list_view);
userInfos=new ArrayList<>();
Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
customListView.setAdapter(customListAdapter);
getDatas();
customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivityCustonlistViewnew.this, "Name : " + names[i] + "\n Profession : " + professions[i], Toast.LENGTH_SHORT).show();
}
});
//sample-----
}
// getting all the datas
private void getDatas(){
for(int count=0;count<names.length;count++){
userInfos.add(new UserInfo(names[count],professions[count],photos[count]));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_option,menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView)menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
newText=newText.toString();
ArrayList<UserInfo> newUserInfos=new ArrayList<>();
for(UserInfo userInfo:userInfos){
String name=userInfo.getName().toLowerCase();
String profession=userInfo.getProfession().toLowerCase();
if(name.contains(newText) || profession.contains(newText)){
newUserInfos.add(userInfo);
}
}
customListAdapter.filterResult(newUserInfos);
customListAdapter.notifyDataSetChanged();
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
my Userinfo.java
public class UserInfo {
private String name,profession;
private int photo;
public UserInfo(){}
public UserInfo(String name, String profession, int photo) {
this.name = name;
this.profession = profession;
this.photo = photo;
}
public String getName() {
return name;
}
public String getProfession() {
return profession;
}
public int getPhoto() {
return photo;
}
}
my customlistAdapter
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter implements View.OnClickListener{
private ArrayList<UserInfo> userInfos;
private Context context;
public CustomListAdapter(ArrayList<UserInfo> userInfos, Context context) {
this.userInfos = userInfos;
this.context = context;
}
#Override
public int getCount() {
return userInfos.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.custom_list_view_layout,null);
ImageView photo,option;
if(view==null){
photo=new ImageView(context);
}
UserInfo userInfo=userInfos.get(i);
photo=(ImageView)view.findViewById(R.id.photo);
option=(ImageView)view.findViewById(R.id.option);
TextView name=(TextView)view.findViewById(R.id.name);
TextView profession=(TextView)view.findViewById(R.id.profession);
photo.setImageResource(userInfo.getPhoto());
name.setText(userInfo.getName());
profession.setText(userInfo.getProfession());
option.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.option:
showPopupMenu(view);
break;
}
}
// getting the popup menu
private void showPopupMenu(View view){
PopupMenu popupMenu=new PopupMenu(context,view);
popupMenu.getMenuInflater().inflate(R.menu.option_menu,popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.edit:
Toast.makeText(context, "Edit !", Toast.LENGTH_SHORT).show();
return true;
case R.id.remove:
Toast.makeText(context, "Remove !", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
}
//file search result
public void filterResult(ArrayList<UserInfo> newUserInfos){
userInfos=new ArrayList<>();
userInfos.addAll(newUserInfos);
notifyDataSetChanged();
}
}
You're adding data from getDatas() but your adapter is already being initialized with empty data. So there are 2 ways :
1 : Initialize and Set adapter after getDatas() call
getDatas();
customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
customListView.setAdapter(customListAdapter);
2 : Inform adapter about dataset changes using notifyDataSetChanged() method
customListView.setAdapter(customListAdapter);
getDatas();
customListAdapter.notifyDataSetChanged();
customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
customListView.setAdapter(customListAdapter);
getDatas();
You are doing wrong here. you are calling customListAdapter and setting cusrom data(userInfos) empty here. Because getDatas() method called after customListAdapter . Hence list will be empty. Just interchange the positron.
getDatas();
customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
customListView.setAdapter(customListAdapter);
Hope It helps.
Thanks
Saurabh
Happy Coding !!!
Related
I need your help. I need your advice for about firestore delete document. I have been working for 2 days this find codes. But everyone told it theoretically. As a last resort, I wanted to write here. How can i get position value ? And how can i delete documents on firestore ? Thank you so much for now your replies...
GorevRecyclerAdapter.java
package com.example.oztekapp;
import android.content.Intent;
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.util.ArrayList;
public class GorevRecyclerAdapter extends RecyclerView.Adapter<GorevRecyclerAdapter.PostHolder> {
private ArrayList <String> adliyeList;
private ArrayList <String> gorevbaslikList;
private ArrayList <String> gorevkonuList;
private ArrayList <String> gorevsaatilist;
private ArrayList <String> gorevtarihiList;
private ArrayList <String> useremailList;
public GorevRecyclerAdapter(ArrayList<String> adliyeList, ArrayList<String> gorevbaslikList, ArrayList<String> gorevkonuList, ArrayList<String> gorevsaatilist, ArrayList<String> gorevtarihiList, ArrayList<String> useremailList) {
this.adliyeList = adliyeList;
this.gorevbaslikList = gorevbaslikList;
this.gorevkonuList = gorevkonuList;
this.gorevsaatilist = gorevsaatilist;
this.gorevtarihiList = gorevtarihiList;
this.useremailList = useremailList;
}
#NonNull
#Override
public PostHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.recycler_row,parent,false);
return new PostHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostHolder holder, int position) {
holder.useremail.setText(useremailList.get(position));
holder.adliye.setText(adliyeList.get(position));
holder.gorevbaslik.setText(gorevbaslikList.get(position));
holder.gorevkonusu.setText(gorevkonuList.get(position));
holder.gorevtarihi.setText(gorevtarihiList.get(position));
holder.gorevsaati.setText(gorevsaatilist.get(position));
}
#Override
public int getItemCount() {
return useremailList.size();
}
class PostHolder extends RecyclerView.ViewHolder{
TextView adliye, gorevkonusu, gorevbaslik, gorevsaati, gorevtarihi, useremail;
public PostHolder(#NonNull final View itemView) {
super(itemView);
adliye = itemView.findViewById(R.id.adliyeTextView);
gorevbaslik = itemView.findViewById(R.id.gorevBaslikTextView);
gorevkonusu = itemView.findViewById(R.id.gorevKonuTextView);
gorevtarihi = itemView.findViewById(R.id.gorevTarihTextView);
gorevsaati = itemView.findViewById(R.id.gorevSaatTextView);
useremail = itemView.findViewById(R.id.userEmailTextView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (itemView.getContext(), GorevDetayActivity.class);
intent.putExtra("gorevbaslik", gorevbaslikList.get(getAdapterPosition()));
intent.putExtra("gorevkonu", gorevkonuList.get(getAdapterPosition()));
intent.putExtra("gorevtarihi", gorevtarihiList.get(getAdapterPosition()));
intent.putExtra("gorevsaati", gorevsaatilist.get(getAdapterPosition()));
v.getContext().startActivity(intent);
}
});
}
}
public void deleteItem(int position){
getSnapshots().getSnapshot(position).getReference().delete();
notifyDataSetChanged();
}
}
and GorevDetayActivity.java
package com.example.oztekapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.StorageReference;
import java.util.ArrayList;
public class GorevDetayActivity extends AppCompatActivity {
private EditText gorevbaslik,gorevkonu,gorevsaat,gorevtarih;
private Button guncelle;
private Spinner adliye;
private ArrayAdapter arrayAdapter;
private AlertDialog.Builder alertDialog;
private FirebaseFirestore firestore;
private ArrayList<String> adliyeList;
private ArrayList <String> gorevbaslikList;
private ArrayList <String> gorevkonuList;
private ArrayList <String> gorevsaatilist;
private ArrayList <String> gorevtarihiList;
private ArrayList <String> useremailList;
private GorevRecyclerAdapter gorevRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gorev_detay);
gorevbaslik = findViewById(R.id.detaygorevbaslik);
gorevkonu = findViewById(R.id.detaygorevkonusu);
gorevtarih = findViewById(R.id.detaytarih);
gorevsaat = findViewById(R.id.detaysaat);
adliye = findViewById(R.id.detayadliye);
firestore = FirebaseFirestore.getInstance();
gorevRecyclerAdapter = new GorevRecyclerAdapter(adliyeList,gorevbaslikList,gorevkonuList,gorevsaatilist,gorevtarihiList,useremailList);
Intent i = getIntent();
String gorevbasligi = i.getStringExtra("gorevbaslik");
String gorevkonusu = i.getStringExtra("gorevkonu");
String gorevtarihi = i.getStringExtra("gorevtarihi");
String gorevsaati = i.getStringExtra("gorevsaati");
gorevbaslik.setText(gorevbasligi);
gorevkonu.setText(gorevkonusu);
gorevtarih.setText(gorevtarihi);
gorevsaat.setText(gorevsaati);
arrayAdapter = ArrayAdapter.createFromResource(this,R.array.adliyeler,android.R.layout.simple_dropdown_item_1line);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
adliye.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menudetay,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull final MenuItem item) {
if (item.getItemId() == R.id.gorevsil)
{
alertDialog = new AlertDialog.Builder(GorevDetayActivity.this);
alertDialog.setTitle("Görev Sil");
alertDialog.setMessage("Görevi silmek istediğinize emin misiniz ?");
alertDialog.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
firestore.collection("Görevler").document().delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(GorevDetayActivity.this,MainActivity.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GorevDetayActivity.this, e.getLocalizedMessage().toString(), Toast.LENGTH_LONG).show();
}
});
}
}).setNegativeButton("Vazgeç", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.create().show();
}
return super.onOptionsItemSelected(item);
}
}
I have tried a lot but my search filter is not working with array of objects and no errors shown.
When the search query is typed all list gets cleared and not working at all or showing query related data in search filter.
Here is the RecyclerViewAdapter.java file:
package com.example.myapplication.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
import com.example.myapplication.model.Contacts;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable
{
private Context context;
List<Contacts> contactsList;
List<Contacts> filterList;
List<Contacts> filteredList;
public RecyclerViewAdapter(Context context, List<Contacts> contactsList)
{
this.context = context;
this.contactsList = contactsList;
filterList = this.contactsList;
Log.d("dbneer","i m");
}
// where to get the single card as viewholder object (DISPLAY FORMAT OF A SINGLE CARD ? OR CREATING A SKELETON DESIGN OF SINGLE CARD)
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
// what will happen after we create the viewholder object I.E. PUTTING VALUES OF SINGLE CARD INTO SKELETON DESIGN OF SINGLE CARD
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position)
{
Contacts contact = contactsList.get(position);
holder.contactName.setText(contact.getName());
holder.phoneNumber.setText(contact.getPhoneNumber());
}
// how many items?
#Override
public int getItemCount()
{
return contactsList.size();
}
// search bar implementation
#Override
public Filter getFilter()
{
return new Filter()
{
// run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
//Log.d("dbneer", "i am here");
if (charSequence.toString().isEmpty())
{
filteredList = filterList;
}
else {
for (Contacts con : filterList) {
// Log.d("dbneer", "hiii" + con.getName() + charSequence.toString().toLowerCase());
if (con.getName().toLowerCase().contains(charSequence.toString().toLowerCase())) {
filteredList.add(con);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
// run on ui thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
if (filterResults != null && filterResults.values != null)
{
contactsList.clear();
contactsList.addAll((Collection<? extends Contacts>) filterResults.values);
/*
for(Contacts c : contactsList)
{
String h = c.getName();
Log.d("dbneer", "working" + h);
}
*/
}
else {
Log.d("dbneer", "not working");
}
notifyDataSetChanged();
}
};
}
// creation of viewholder object:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView contactName;
public TextView phoneNumber;
public ImageView iconButton;
public ViewHolder(#NonNull View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
contactName = itemView.findViewById(R.id.name);
phoneNumber = itemView.findViewById(R.id.phone_number);
iconButton = itemView.findViewById(R.id.imageView);
iconButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
// Log.d("viewholder", "Clicked");
int position = this.getAdapterPosition();
Contacts contact = contactsList.get(position);
String name = contact.getName();
String phone = contact.getPhoneNumber();
Toast.makeText(context, "The position is" + String.valueOf(position) + "Name is"
+ name + " Phone is " + phone, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, com.example.myapplication.displayContact.class);
intent.putExtra("Rname", name);
intent.putExtra("Rphone", phone);
context.startActivity(intent);
}
}
}
Activity3.java:
package com.example.myapplication;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import com.example.myapplication.adapter.RecyclerViewAdapter;
// MySqlLite mydbhandler libraries:
import com.example.myapplication.data.MyDbHandler;
import com.example.myapplication.model.Contacts;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
//firebase database libraries:
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Activity3 extends AppCompatActivity
{
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
ArrayList<Contacts> contactsArrayList = new ArrayList<>();
//List<Contacts> contactsList;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference reff;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
//Recyclerview initialization
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
/*
// creating mydbhandler class object:
MyDbHandler db = new MyDbHandler(Activity3.this);
//deleting all rows:
//db.deleteAll();
// creating contact object:
Contacts teer = new Contacts();
teer.setPhoneNumber("9999900000");
teer.setName("Neer");
teer.setState("Haryana");
db.addContact(teer);
// get all contacts
contactsList = db.getAllContacts();
for(Contacts contact : contactsList)
{
Log.d("dbneer","Id: " + contact.getId() + "\n"
+ "Name: " + contact.getName() + "\n" +
"Phone Number: " + contact.getPhoneNumber() + "\n" + "State:" + contact.getState());
contactsArrayList.add(contact);
}
*/
//using firebase database handing:
// contact = new Contacts();
try
{
firebaseDatabase = FirebaseDatabase.getInstance();
reff = firebaseDatabase.getReferenceFromUrl("https://myapplication-6539a.firebaseio.com/").child("shivam");
}
catch(Exception e)
{
Log.d("dberror","database error");
e.printStackTrace();
}
reff.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// get all children objects at this level
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
// shake hands with each of the child
for(DataSnapshot child : children)
{
Contacts contact = child.getValue(Contacts.class);
// firebase testing :
Log.d("dbneer","id is "+contact.getId());
Log.d("dbneer","name is "+contact.getName());
Log.d("dbneer","phone number is "+contact.getPhoneNumber());
Log.d("dbneer","state is "+contact.getState());
contactsArrayList.add(contact);
}
// Use your recyclerview
recyclerViewAdapter = new RecyclerViewAdapter(Activity3.this, contactsArrayList);
recyclerView.setAdapter(recyclerViewAdapter);
// Finally, you have nailed it bro!! did your realtime database operation...!
Log.d("dbneer","reached in recycler view area");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//menu bar search fuctionality:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, 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)
{
recyclerViewAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText)
{
recyclerViewAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
Contacts.java:
package com.example.myapplication.model;
// change long datatype of phonenumber into string while dealing with sql-lite and viceversa for firebase:
public class Contacts
{
private int id;
private String name;
private String phoneNumber;
private String state;
public Contacts(String name, String phoneNumber, String state)
{
this.name = name;
this.phoneNumber = phoneNumber;
this.state = state;
}
public Contacts(int id, String name, String phoneNumber, String state)
{
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.state = state;
}
public Contacts()
{
}
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 getPhoneNumber()
{
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
}
Nothing shows up on running code in search filter as all list objects vanishes and never returned even after returning back from search filter.
I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}
I currently have implemented RecyclerView, but my CarView does not show the data.
These are my current data in Firebase:
But the RecyclerView shows all three CardViews, but without the records:
These are the files I'm using:
DomiciliarySearchFragment.java
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.didierzuniga.domix.R;
import com.didierzuniga.domix.adapter.OrderAdapterRecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {#link Fragment} subclass.
*/
public class DomiciliarySearchFragment extends Fragment {
#Bind(R.id.recycler_order) RecyclerView recyclerView;
public DomiciliarySearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_domiciliary_search, container, false);
showToolbar(getResources().getString(R.string.tab_search), true, view);
ButterKnife.bind(this, view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("order");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, String> values = (HashMap<String, String>) dataSnapshot.getValue();
recyclerView.setAdapter(new OrderAdapterRecyclerView(values));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});
return view;
}
private class GetDataFromFirebase extends AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
public void showToolbar(String tittle, boolean upButton, View view){
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(tittle);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
}
}
OrderAdapterRecyclerView.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.didierzuniga.domix.R;
import java.util.HashMap;
import java.util.Map;
public class OrderAdapterRecyclerView extends RecyclerView.Adapter<OrderAdapterRecyclerView.ViewHolder>{
private HashMap<String, String> values;
public OrderAdapterRecyclerView(HashMap<String, String> values) {
this.values = values;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_order,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.fromm.setText(values.get(position));
holder.too.setText(values.get(position));
holder.moneyToPayy.setText(values.get(position));
}
#Override
public int getItemCount() {
return values.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView fromm;
private TextView too;
private TextView moneyToPayy;
ViewHolder(View itemView) {
super(itemView);
fromm = (TextView) itemView.findViewById(R.id.from);
too = (TextView) itemView.findViewById(R.id.to);
moneyToPayy = (TextView) itemView.findViewById(R.id.moneyToPay);
}
}
}
Model: Order.java
public class Order {
public String uid;
public String oFrom;
public String oTo;
public String oHeader;
public String oDescription;
public String oMoneyToPay;
public String oAuthor;
public boolean completed;
public Order(){
}
public Order(String oFrom, String oTo, String oHeader, String oDescription, String oMoneyToPay, String oAuthor) {
this.oFrom = oFrom;
this.oTo = oTo;
this.oHeader = oHeader;
this.oDescription = oDescription;
this.oMoneyToPay = oMoneyToPay;
this.oAuthor = oAuthor;
this.completed = false;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getoFrom() {
return oFrom;
}
public void setoFrom(String oFrom) {
this.oFrom = oFrom;
}
public String getoTo() {
return oTo;
}
public void setoTo(String oTo) {
this.oTo = oTo;
}
public String getoHeader() {
return oHeader;
}
public void setoHeader(String oHeader) {
this.oHeader = oHeader;
}
public String getoDescription() {
return oDescription;
}
public void setoDescription(String oDescription) {
this.oDescription = oDescription;
}
public String getoMoneyToPay() {
return oMoneyToPay;
}
public void setoMoneyToPay(String oMoneyToPay) {
this.oMoneyToPay = oMoneyToPay;
}
public String getoAuthor() {
return oAuthor;
}
public void setoAuthor(String oAuthor) {
this.oAuthor = oAuthor;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
¿What I need to do to be able to display the registers in each CardView?
Thank you!
In DomiciliarySearchFragment.java /onDataChange,
Can you confirm that hashmap has been correctly populated?
I had a similar problem, but the reason was that the data was not stored correctly in the collection
Thanks uguboz, I should have use dataSnapshot.getChildren(), and get all the records one by one in a loop
rv = (RecyclerView) view.findViewById(R.id.recycler_order);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
orders = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new OrderAdapter(orders);
rv.setAdapter(adapter);
database.getReference().child("order").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
orders.removeAll(orders);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Order order = snapshot.getValue(Order.class);
orders.add(order);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you everyone.
Solved , I should use Static for my Models in declerating . thanks all
I just went through this topic filter recycler view using search view and I did all the steps. Now when I search in recycler view it will filter my recycler view but when I press back space and remove a char it wont show the removed items! My recycler view is also empty after the search.
This is my RecyclerView adapter:
package com.webapp.masoud.application.myRecyclerAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.webapp.masoud.application.R;
import com.webapp.masoud.application.service.NewsModel;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class myRecyclerAdapter extends RecyclerView.Adapter<myRecyclerAdapter.myRecyclerViewHolder> {
private Context context;
ArrayList<NewsModel> myModels;
public myRecyclerAdapter(Context context, ArrayList<NewsModel> myModels) {
this.context = context;
this.myModels = myModels;
}
#Override
public myRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.channels_layout, parent, false);
return new myRecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(myRecyclerViewHolder holder, int position) {
final NewsModel newsModel = myModels.get(position);
holder.edt_Title.setText(newsModel.title);
holder.edt_Dis.setText(newsModel.discription);
holder.txt_Category.setText(newsModel.category);
Picasso.with(context).load(newsModel.image).into(holder.img_Channel);
holder.btn_Join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username;
if (newsModel.username.startsWith("#")){
username = "http://telegram.me/" + newsModel.username.substring(1);
}
else{
username = "http://telegram.me/" + newsModel.username;}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(username));
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return myModels.size();
}
public void animateTo(ArrayList<NewsModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
public void setModels(ArrayList<NewsModel> models) {
myModels = new ArrayList<>(models);
}
public NewsModel removeItem(int position) {
final NewsModel model = myModels.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, NewsModel model) {
myModels.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final NewsModel model = myModels.remove(fromPosition);
myModels.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
private void applyAndAnimateRemovals(ArrayList<NewsModel> newModels) {
for (int i = myModels.size() - 1; i >= 0; i--) {
final NewsModel model = myModels.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(ArrayList<NewsModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final NewsModel model = newModels.get(i);
if (!myModels.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(ArrayList<NewsModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final NewsModel model = newModels.get(toPosition);
final int fromPosition = myModels.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
class myRecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView edt_Title;
private TextView edt_Dis;
public TextView txt_Category;
private Button btn_Join;
private CircleImageView img_Channel;
public myRecyclerViewHolder(View itemView) {
super(itemView);
edt_Title = (TextView) itemView.findViewById(R.id.edt_Title);
edt_Dis = (TextView) itemView.findViewById(R.id.edt_Dis);
btn_Join = (Button) itemView.findViewById(R.id.btn_Join);
img_Channel = (CircleImageView) itemView.findViewById(R.id.img_Channel);
txt_Category = (TextView) itemView.findViewById(R.id.txt_Category);
}
}
}
This is my MainActivity.java:
package com.webapp.masoud.application.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Parcelable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.webapp.masoud.application.R;
import com.webapp.masoud.application.myRecyclerAdapter.myRecyclerAdapter;
import com.webapp.masoud.application.service.NewsModel;
import com.webapp.masoud.application.service.APIService;
import com.webapp.masoud.application.service.NewsModelResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity {
private SearchView mSearchView;
private MenuItem searchMenuItem;
RecyclerView rv_Channels;
private Parcelable recyclerViewState;
SearchView.OnQueryTextListener myListener;
myRecyclerAdapter myAdapter;
ArrayList<NewsModel> newsModelArrayList;
NewsModelResponse newsModelResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//CalliGraphy
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Vazir.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
//Context
setContentView(R.layout.activity_main);
//MY Application
Toolbar myToolbar = (Toolbar) findViewById(R.id.myToolbar);
setSupportActionBar(myToolbar);
final ProgressDialog myProgressDialog = new ProgressDialog(MainActivity.this);
myProgressDialog.setMessage("در حال دریافت لیست کانال ها ، لطفا منتظر بمانید .");
rv_Channels = (RecyclerView) findViewById(R.id.rv_Channels);
final SearchView sv_Channels = (SearchView) findViewById(R.id.sv_Channels);
//My API Service !
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://rapcity1.cf/service/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<NewsModelResponse> serviceNewsModels = service.getNewsModels();
serviceNewsModels.enqueue(new Callback<NewsModelResponse>() {
#Override
public void onResponse(Call<NewsModelResponse> call, Response<NewsModelResponse> response) {
myProgressDialog.dismiss();
newsModelResponse = response.body();
newsModelArrayList = newsModelResponse.getNewsModels();
myAdapter = new myRecyclerAdapter(MainActivity.this, newsModelArrayList);
LinearLayoutManager myLinearlayoutmanager = new LinearLayoutManager(MainActivity.this);
rv_Channels.setLayoutManager(myLinearlayoutmanager);
recyclerViewState = rv_Channels.getLayoutManager().onSaveInstanceState();//save
rv_Channels.setItemAnimator(new DefaultItemAnimator());
rv_Channels.setAdapter(myAdapter);
}
#Override
public void onFailure(Call<NewsModelResponse> call, Throwable t) {
}
});
//End of API Service
//Search
assert sv_Channels != null;
myListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final ArrayList<NewsModel> filteredModelList = filter(newsModelArrayList, query);
myAdapter.animateTo(filteredModelList);
rv_Channels.scrollToPosition(0);
return true;
}
};
}
private ArrayList<NewsModel> filter(ArrayList<NewsModel> models, String query) {
// query = query.toLowerCase();
final ArrayList<NewsModel> filteredModelList = new ArrayList<>();
for (NewsModel model : models) {
final String title = model.title;
//final String dis = model.discription;
if (title.contains(query) /*|| dis.contains(query)*/) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#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);
searchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView.setOnQueryTextListener(myListener);
mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
rv_Channels.getLayoutManager().onRestoreInstanceState(recyclerViewState);
return true;
}
});
return true;
}
}
This is my newsModels:
package com.webapp.masoud.application.service;
import java.io.Serializable;
/**
* Created by Master on 4/19/2016.
*/
public class NewsModel implements Serializable {
public String id;
public String title;
public String discription;
public String image;
public String category;
public String username;
public NewsModel(String title, String description,String image,String id,String category,String username) {
this.id = id;
this.title = title;
this.discription = description;
this.image = image;
this.category = category;
this.username=username;
}
public NewsModel() {
}
}
Please help me, thanks. Sorry for my bad English!
I am also using the tutorial and get it done. I just implements my Activity with
implements SearchView.OnQueryTextListener
Also i am using searchview this way.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.close_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
and rest the overrided methods, Not sure although give a try.