// Category Adapter which open the second fragment containing the blank recyclerview(which should ideally contain intial data.)
public class MyCategoryAdapter extends RecyclerView.Adapter<MyCategoryHolder> {
private Context context;
private ArrayList<Categories> categories;
private Context context1;
public MyCategoryAdapter(Context context, ArrayList<Categories> categories) {
this.context = context;
this.categories = categories;
}
#Override
public MyCategoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_model, parent, false);
context1 = parent.getContext();
return new MyCategoryHolder(v);
}
#Override
public void onBindViewHolder(MyCategoryHolder holder, final int position) {
Categories c = categories.get(position);
holder.categoryText.setText(c.getName());
holder.categoryIdText.setText(c.getId());
//item click
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
Toast.makeText(context.getApplicationContext(), Integer.toString(pos), Toast.LENGTH_SHORT).show();
openActivity();
}
});
}
#Override
public int getItemCount() {
return categories.size();
}
private void openActivity()
{
FragmentActivity fragment = ((FragmentActivity)context1);
fragment.getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment_container, new SubCategoryFragment()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
}
I have made an android app containing of 2 Recyclerviews. Both have their individual Realm databases. First Recyclerview displays the Categories. When I click on any items, it opens the second Recyclerview for me (containing Subcategories). I am able to load the initial data for the Categories recyclerview but when i click on any items in it, it opens a blank recyclerview (ideally should display the contents from the SubCategories intial data Realm database)
//Realm for SubCategories
public class SubCategories extends RealmObject{
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//Categories intial data
public class CategoriesInitialData implements Realm.Transaction {
#Override
public void execute(Realm realm) {
Categories categories = new Categories();
categories.setName("Animals");
categories.setId("0");
realm.insertOrUpdate(categories);
categories.setName("Birds");
categories.setId("1");
realm.insertOrUpdate(categories);
categories.setName("Mountains");
categories.setId("2");
realm.insertOrUpdate(categories);
categories.setName("Instagram");
categories.setId("3");
realm.insertOrUpdate(categories);
categories.setName("Facebook");
categories.setId("4");
realm.insertOrUpdate(categories);
categories.setName("Twitter");
categories.setId("5");
realm.insertOrUpdate(categories);
categories.setName("OnePlus");
categories.setId("6");
realm.insertOrUpdate(categories);
categories.setName("Apple");
categories.setId("7");
realm.insertOrUpdate(categories);
categories.setName("Samsung");
categories.setId("8");
realm.insertOrUpdate(categories);
categories.setName("Laptops");
categories.setId("9");
realm.insertOrUpdate(categories);
categories.setName("Food");
categories.setId("10");
realm.insertOrUpdate(categories);
categories.setName("Lifestyle");
categories.setId("11");
realm.insertOrUpdate(categories);
}
#Override
public int hashCode() {
return CategoriesInitialData.class.hashCode();
}
#Override
public boolean equals(Object obj) {
return obj != null && obj instanceof CategoriesInitialData;
}
}
// SubCategories Initial Data
public class SubCategoriesInitialData implements Realm.Transaction {
#Override
public void execute(Realm realm) {
SubCategories subCategories = new SubCategories();
subCategories.setName("Animals1");
subCategories.setId("0");
realm.insertOrUpdate(subCategories);
subCategories.setName("Animals2");
subCategories.setId("0");
realm.insertOrUpdate(subCategories);
subCategories.setName("Animals3");
subCategories.setId("0");
realm.insertOrUpdate(subCategories);
subCategories.setName("Birds1");
subCategories.setId("1");
realm.insertOrUpdate(subCategories);
subCategories.setName("Birds2");
subCategories.setId("1");
realm.insertOrUpdate(subCategories);
subCategories.setName("Birds3");
subCategories.setId("1");
realm.insertOrUpdate(subCategories);
}
#Override
public int hashCode() {
return SubCategoriesInitialData.class.hashCode();
}
#Override
public boolean equals(Object obj) {
return obj != null && obj instanceof SubCategoriesInitialData;
}
}
// Category Fragment
public class CategoryFragment extends Fragment {
Realm realm;
MyCategoryAdapter myCategoryAdapter;
RealmChangeListener realmChangeListener;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_categories,container,false);
final RecyclerView rv = (RecyclerView) myView.findViewById(R.id.categoryRV);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//Realm configuration
Realm.init(getContext());
RealmConfiguration configuration = new RealmConfiguration.Builder().initialData(new CategoriesInitialData()).deleteRealmIfMigrationNeeded().build();
realm = Realm.getInstance(configuration);
//Save
final CategoriesRealmHelper helper = new CategoriesRealmHelper(realm);
//Categories categories = new Categories();
//categories.setName("Last Category");
//helper.save(categories);
//retrieve
helper.retrieveCategories();
//setup adapter
myCategoryAdapter = new MyCategoryAdapter(getContext(), helper.refreshCategories());
rv.setAdapter(myCategoryAdapter);
//data change
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object element) {
//refresh
myCategoryAdapter = new MyCategoryAdapter(getContext(), helper.refreshCategories());
rv.setAdapter(myCategoryAdapter);
}
};
//add changes to realm
realm.addChangeListener(realmChangeListener);
return myView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
#Override
public void onStop() {
super.onStop();
}
}
// SubCategories Fragment
public class SubCategoryFragment extends Fragment {
Realm realm;
MySubCategoryAdapter mySubCategoryAdapter;
RealmChangeListener realmChangeListener;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_subcategories, container, false);
final RecyclerView rv = (RecyclerView) myView.findViewById(R.id.subcategoryRV);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//Realm configuration
Realm.init(getContext());
RealmConfiguration configuration = new RealmConfiguration.Builder().initialData(new SubCategoriesInitialData()).deleteRealmIfMigrationNeeded().build();
realm = Realm.getInstance(configuration);
//Save
final SubCategoriesRealmHelper helper = new SubCategoriesRealmHelper(realm);
//SubCategories subCategories = new SubCategories();
//subCategories.setName("Hello");
//helper.save(subCategories);
//retrieve
helper.retrieveSubCategories();
//setting up adapter
mySubCategoryAdapter = new MySubCategoryAdapter(getContext(), helper.refreshSubCategories());
rv.setAdapter(mySubCategoryAdapter);
//data change
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object element) {
//refresh
mySubCategoryAdapter = new MySubCategoryAdapter(getContext(), helper.refreshSubCategories());
rv.setAdapter(mySubCategoryAdapter);
}
};
//add changes to realm
realm.addChangeListener(realmChangeListener);
return myView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
#Override
public void onStop() {
super.onStop();
}
}
// Realm Helper class. I also have a CategoriesRealmHelper class having similar methods
public class SubCategoriesRealmHelper {
Realm realm;
boolean saved;
RealmResults<SubCategories> subCategories;
public SubCategoriesRealmHelper(Realm realm) {
this.realm = realm;
}
//Writing data to subcategories database
public boolean save(final SubCategories subCategories)
{
if(subCategories == null)
{
saved = false;
}
else
{
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try{
realm.copyToRealm(subCategories);
saved = true;
}catch (RealmException e)
{
e.printStackTrace();
saved = false;
}
}
});
}
return saved;
}
//reading data from subcategories database
public void retrieveSubCategories()
{
subCategories = realm.where(SubCategories.class).findAll();
}
//refreshing subcategories data
public ArrayList<SubCategories> refreshSubCategories()
{
ArrayList<SubCategories> latest = new ArrayList<>();
for (SubCategories s : subCategories) {
latest.add(s);
}
return latest;
}
}
//Main Acitivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openFragment();
}
void openFragment(){
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new CategoryFragment()).commit();
}
}
//Realm for Categories
public class Categories extends RealmObject {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Related
Those are categories and subcategories. There can be subcategory or not.
JsonCode to be used is as below.
categoryId is what will change to call subcategories.
E.g. If you want to see subcategories of cars
Json Code
[{"Id":1,"TitleEN":"Cars","TitleAR":"سيارات","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/ce686544-9f51-4213-b5db-7c015b788e8d.png","ProductCount":"3","HaveModel":"0","SubCategories":[{"Id":6,"TitleEN":"Cat6","TitleAR":"قسم6","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/ce686544-9f51-4213-b5db-7c015b788e8d.png","ProductCount":"3","HaveModel":"0","SubCategories":[]}]},{"Id":2,"TitleEN":"Cat2","TitleAR":"قسم2","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"8","HaveModel":"0","SubCategories":[{"Id":13,"TitleEN":"cat1 -1 ","TitleAR":"cat1 - 1","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"8","HaveModel":"0","SubCategories":[]}]},{"Id":3,"TitleEN":"Cat3","TitleAR":"قسم3","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"2","HaveModel":"0","SubCategories":[]},{"Id":4,"TitleEN":"Cat4","TitleAR":"قسم4","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"1","HaveModel":"0","SubCategories":[]},{"Id":5,"TitleEN":"Cat5","TitleAR":"قسم5","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"0","HaveModel":"0","SubCategories":[]},{"Id":8,"TitleEN":"Cat8","TitleAR":"قسم8","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"0","HaveModel":"0","SubCategories":[]},{"Id":9,"TitleEN":"Slide01","TitleAR":"Slide02","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/2ba07cb2-49a0-47e4-aba6-ef10a916fb12.png","ProductCount":"0","HaveModel":"0","SubCategories":[]}]
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
public ArrayList<String> images = new ArrayList<String>();
}
Movie Model
public class Movie implements Parcelable {
public String TitleEN;
public String TitleAR;
public String Photo;
public int id;
public Movie(){
}
protected Movie(Parcel in) {
TitleEN = in.readString();
TitleAR = in.readString();
Photo = in.readString();
id = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(TitleEN);
dest.writeString(TitleAR);
dest.writeString(Photo);
dest.writeInt(id);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
Fragament_main
public class Fragament_main extends Fragment {
public View mainFragmentView;
public String LOG_TAG = "ShowcaseFragment";
public ArrayList<Movie> movies = new ArrayList<Movie>();
private RequestQueue mRequestQueue;
public ImageAdapter imageAdapter;
public static Fragament_main instance;
GridView gridview;
public boolean isDualPane = false;
// static to preserve sorting over orientation changes (activity restart)
public static String sortOrder = "popularity.desc", moreParams = "";
public static boolean setting_cached = false;
public int gridPos = -1;
public Fragament_main() {
// Required empty public constructor
instance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainFragmentView = inflater.inflate(R.layout.fragment_main, container, false);
mRequestQueue = Volley.newRequestQueue(getContext());
// setup adapters
imageAdapter = new ImageAdapter(getContext());
gridview = (GridView) mainFragmentView.findViewById(R.id.gridView);
gridview.setAdapter(imageAdapter);
//updateUI(setting_cached);
//gridview.setOnItemClickListener(new GridClickListener());
// manage grid col count wrt Orientation
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
setGridColCount(3);
else
setGridColCount(2);
return mainFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("GRIDVIEW_POSITION", gridview.getFirstVisiblePosition());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
gridPos = savedInstanceState.getInt("GRIDVIEW_POSITION");
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRequestQueue.cancelAll(new RequestQueue.RequestFilter() {
#Override
public boolean apply(Request<?> request) {
return true;
}
});
}
/*class GridClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (isDualPane){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
DetailActivityFragment detailActivityFragment = DetailActivityFragment.newInstance(movies.get(position));
ft.replace(R.id.detailContainer, detailActivityFragment);
ft.commit();
} else {
Intent intent = new Intent(getContext(), DetailActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, (Parcelable) movies.get(position));
startActivity(intent);
}
}
}*/
/* public void updateUI(boolean cached){
movies.clear();
imageAdapter.clearItems();
setting_cached = cached;
if (!cached)
getMovies(sortOrder, moreParams);
else
getFavorites();
}
*/
public void getMovies(String sortOrder, String moreParams){
String url = "http://souq.hardtask.co/app/app.asmx/GetCategories?categoryId=0&countryId=1";
JsonObjectRequest req = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray items = response.getJSONArray("results");
JSONObject movieObj;
for (int i=0; i<items.length(); i++){
movieObj = items.getJSONObject(i);
Movie movie = new Movie();
movie.id = movieObj.getInt("id");
movie.TitleEN = movieObj.getString("original_title");
movie.TitleAR = movieObj.getString("overview");
movie.Photo = "http://souq.hardtask.co/app/app.asmx/GetCategories?categoryId=0&countryId=1" + movieObj.getString("poster_path");
movies.add(movie);
// Add image to adapter
imageAdapter.addItem(movie.Photo);
}
} catch (JSONException e){
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
gridview.setAdapter(imageAdapter);
if (gridPos > -1)
gridview.setSelection(gridPos);
gridPos = -1;
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(LOG_TAG, "Error in JSON Parsing");
}
});
mRequestQueue.add(req);
}
/* public void getFavorites(){
movies.addAll((new MoviesDB()).getFavoriteMovies(getContext().getContentResolver()));
for (Movie movie : movies){
imageAdapter.addItem(movie.Photo);
}
gridview.setAdapter(imageAdapter);
if (gridPos > -1)
gridview.setSelection(gridPos);
gridPos = -1;
}*/
public void updateFavoritesGrid(){
if (setting_cached) {
int p = gridview.getLastVisiblePosition();
///updateUI(true);
gridview.smoothScrollToPosition(p);
}
}
public void setGridColCount(int n){
((GridView) mainFragmentView.findViewById(R.id.gridView)).setNumColumns(n);
}
}
I don't know how to add Json data into GridView.
Could you help me?
Go through this example to view images in grid,
Convert your jsonArray into an ArrayList by using,
ArrayList<Cars> carsList = new Gson().fromJson(jsonArrayYouHave.toString(),new TypeToken<List<Cars>>() {
}.getType());
Pass this Array to your Adapter.
Use this POJO,
public class Cars {
private String TitleAR;
private String HaveModel;
private String TitleEN;
private String Id;
private ArrayList<SubCategories> SubCategories;
private String Photo;
private String ProductCount;
//Todo please add getter/setters for class Cars variables here
public class SubCategories {
private String TitleAR;
private String HaveModel;
private String TitleEN;
private String Id;
private ArrayList<String> SubCategories;
private String Photo;
private String ProductCount;
//Todo please add getter/setters for class SubCategories variables here
}
I'll suggest to use Retrofit as it'll provide you parsed arraylist which is converted into Response POJO you have provided. You can find many examples for Retrofit.
Step 1
Add the following dependencies in your app level gradle file.Dependencies are for retrofit, gsonConvertor butterknife and glide.
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation('com.squareup.retrofit2:retrofit:2.1.0') {
// exclude Retrofit’s OkHttp dependency module and define your own module import
exclude module: 'okhttp'
}
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
Step 2 Create a class by name ApiClient and paste the following code in this class
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("http://souq.hardtask.co")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
Step 3 Create a new Interface class by name APIInterface and paste the following code in this class
#GET("/app/app.asmx/GetCategories")
Call<List<Product>> getProducts(#QueryMap Map<String, String> params);
Step 4 Create POJO classes according to json response. We have two classes Products and their subcategory.So I am creating first class by name Product
public class Product {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("Photo")
#Expose
private String photo;
#SerializedName("ProductCount")
#Expose
private String productCount;
#SerializedName("HaveModel")
#Expose
private String haveModel;
#SerializedName("SubCategories")
#Expose
private List<SubCategory> subCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getProductCount() {
return productCount;
}
public void setProductCount(String productCount) {
this.productCount = productCount;
}
public String getHaveModel() {
return haveModel;
}
public void setHaveModel(String haveModel) {
this.haveModel = haveModel;
}
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
}
And SubCategory
public class SubCategory {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("Photo")
#Expose
private String photo;
#SerializedName("ProductCount")
#Expose
private String productCount;
#SerializedName("HaveModel")
#Expose
private String haveModel;
#SerializedName("SubCategories")
#Expose
private List<Object> subCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getProductCount() {
return productCount;
}
public void setProductCount(String productCount) {
this.productCount = productCount;
}
public String getHaveModel() {
return haveModel;
}
public void setHaveModel(String haveModel) {
this.haveModel = haveModel;
}
public List<Object> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<Object> subCategories) {
this.subCategories = subCategories;
}
}
Step 5 now we need a view for recyclerview holder(in your case gridview layout). For that we need to create a new layout file inside layout folder. you can name it li_product_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="200dp">
<ImageView
android:id="#+id/ImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/ImageView"
android:layout_alignTop="#id/ImageView"
android:layout_alignRight="#id/ImageView"
android:layout_alignBottom="#id/ImageView"
android:text="#string/app_name"
android:gravity="bottom|right" />
</RelativeLayout>
</RelativeLayout>
Step 6 Now we need itemHolder to hold the view for that purpose we will create a new class by name ProductsItemHolderand will have the following code
public class ProductsItemHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ImageView)
ImageView imageView;
#BindView(R.id.tv_title)
TextView textView;
public ProductsItemHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
public void bindData(Product datum, int position, int size) {
Glide.with(itemView)
.asBitmap()
.load(datum.getPhoto())
.into(imageView);
textView.setText(datum.getTitleAR());
}
}
Step 7 Now we need adapter which contains the data to present inside recyclerview. Create a new class by name ProductsAdapter and paste the following code inside this class
public class ProductsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Product> mList;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.li_product_view, viewGroup, false);
return new ProductsItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
int size= mList.size();
((ProductsItemHolder) viewHolder).bindData(mList.get(position), position,size);
}
#Override
public int getItemCount() {
return mList.size();
}
public void setData(List<Product> userLists) {
this.mList = userLists;
notifyDataSetChanged();
}
}
Step 8 now inside the activity or fragment we need to get response from json and pass this response to recyclerview.
public class MainActivity extends AppCompatActivity {
APIInterface apiInterfacePages;
RecyclerView recyclerView;
List<MultipleResource.Datum> datumList= new ArrayList<>();
ProgressDialog dialog;
ProductsAdapter productsAdapter;
private List<Product> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
recyclerView= findViewById(R.id.recyclerView);
productsAdapter= new ProductsAdapter();
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
getData();
}
private void getData() {
dataArrayList = new ArrayList<>();
Map<String, String> params = new HashMap<String, String>();
params.put("categoryId", "0");
params.put("countryId", "1");
Call<List<Product>> call= apiInterfacePages.getProducts(params);
call.enqueue(new Callback<List<Product>>() {
#Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
dataArrayList = response.body();
productsAdapter.setData(dataArrayList);
recyclerView.setAdapter(productsAdapter);
}
#Override
public void onFailure(Call<List<Product>> call, Throwable t) {
Log.i("Call response",t.getMessage());
}
});
}
}
In my application I want use two recyclerView into one Activity.
I want when click on items of one of this recylerView's items , add item to another recyclerView.
I write below codes, when click on items just add lasted item info to another recyclerView.
But I want when click on each items, add this each items into another recyclerView not just add lasted items.
Now just add lasted items, but I want click each item add this item.
My Activity code:
public class SuggestFilmActivity extends AppCompatActivity implements SuggestedListener {
#BindView(R.id.toolbarTitleTxt)
TextView toolbarTitleTxt;
#BindView(R.id.suggestFilm_searchEditText)
EditText suggestFilm_searchEditText;
#BindView(R.id.suggestFilm_searchBtn)
ImageView suggestFilm_searchBtn;
#BindView(R.id.suggestFilm_recyclerView)
RecyclerView suggestFilm_recyclerView;
#BindView(R.id.suggestFilm_recyclerViewProgress)
ProgressBar suggestFilm_recyclerViewProgress;
#BindView(R.id.newsPageLoadLay)
RelativeLayout newsPageLoadLay;
#BindView(R.id.suggestFilm_recyclerViewSendUser)
RecyclerView suggestFilm_recyclerViewSendUser;
private Context context;
private SuggestFilmAdapter suggestFilmAdapter;
private SuggestFilmUserAdapter suggestFilmUserAdapter;
private List<Result> model = new ArrayList<>();
private InterfaceApi api;
private SharedPrefrencesHandler prefrencesHandler;
private String token;
private GridLayoutManager gridLayoutManager;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggest_film);
//Initialize
ButterKnife.bind(this);
context = this;
prefrencesHandler = new SharedPrefrencesHandler(context);
api = ApiClient.getClient().create(InterfaceApi.class);
suggestFilmAdapter = new SuggestFilmAdapter(context, model, this);
gridLayoutManager = new GridLayoutManager(context, 3);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//Get token
token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
//Set toolbar title
toolbarTitleTxt.setText(context.getResources().getString(R.string.SuggestToFollowers));
//Init followers recyclerView
suggestFilm_recyclerView.setLayoutManager(gridLayoutManager);
suggestFilm_recyclerView.setHasFixedSize(true);
//Init send user recyclerView
suggestFilm_recyclerViewSendUser.setLayoutManager(linearLayoutManager);
suggestFilm_recyclerViewSendUser.setHasFixedSize(true);
//Load more
newsPageLoadLay.setVisibility(View.GONE);
suggestFilm_recyclerView.setOnScrollListener(new EndlessRecyclerGridPage1(gridLayoutManager) {
#Override
public void onLoadMore(int current_page) {
newsPageLoadLay.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(current_page));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
if (response.body().getData().getResult().size() > 0) {
suggestFilmAdapter.addNewItem(response.body().getData().getResult());
//Gone no explore
newsPageLoadLay.setVisibility(View.GONE);
}
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
newsPageLoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
newsPageLoadLay.setVisibility(View.GONE);
}
});
}
});
//Get user data
getUserData();
}
private void getUserData() {
suggestFilm_recyclerViewProgress.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(1));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getData().getResult().size() > 0
&& response.body().getStatusCode() != 401 && response.body().getStatusCode() != 402) {
model.clear();
model.addAll(response.body().getData().getResult());
suggestFilmAdapter.notifyDataSetChanged();
suggestFilm_recyclerView.setAdapter(suggestFilmAdapter);
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
});
}
private SuggestFilmSendData filmSendData(int page) {
SuggestFilmSendData sendData = new SuggestFilmSendData();
sendData.setKeyword("");
sendData.setPageIndex(page);
sendData.setPageSize(10);
return sendData;
}
private ArrayList<SuggestFilmAddUser> prepareData(int id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = new ArrayList<>();
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
return suggestFilmAddUserList;
}
#Override
public void onSend(int Id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = prepareData(Id, name, image);
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context, suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
}
}
One recyclerView adapter and send data Interface codes:
public class SuggestFilmAdapter extends RecyclerView.Adapter<SuggestFilmAdapter.ViewHolder> {
private Context context;
private List<Result> model;
private SuggestedListener suggestedListener;
public SuggestFilmAdapter(Context context, List<Result> model, SuggestedListener suggestedListener) {
this.context = context;
this.model = model;
this.suggestedListener = suggestedListener;
}
#Override
public SuggestFilmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suggest_film_users_followers, parent, false);
return new SuggestFilmAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final SuggestFilmAdapter.ViewHolder holder, final int position) {
//Name
holder.row_suggestFilmProfileName.setText(model.get(position).getName());
//Image
Glide.with(context)
.load(model.get(position).getImageUrl())
.asBitmap()
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(300, 300)
.into(new BitmapImageViewTarget(holder.row_suggestFilmProfileImage) {
#Override
protected void setResource(Bitmap resource) {
if (context == null) return;
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.row_suggestFilmProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
//Is Mutual
if (model.get(position).getIsMutual()) {
holder.row_suggestFilmIsOk.setVisibility(View.VISIBLE);
} else {
holder.row_suggestFilmIsOk.setVisibility(View.GONE);
}
holder.row_suggestedLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestedListener.onSend(model.get(position).getUserId(),
model.get(position).getName(),
model.get(position).getImageUrl());
}
});
}
#Override
public int getItemCount() {
return model.size();
}
public void addNewItem(List<Result> newContent) {
int start = this.model.size();
int end = newContent.size();
model.addAll(newContent);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_suggestFilmProfileImage, row_suggestFilmIsOk;
private TextView row_suggestFilmProfileName;
private RelativeLayout row_suggestedLay;
public ViewHolder(View itemView) {
super(itemView);
row_suggestFilmProfileImage = (ImageView) itemView.findViewById(R.id.row_suggestFilmProfileImage);
row_suggestFilmIsOk = (ImageView) itemView.findViewById(R.id.row_suggestFilmIsOk);
row_suggestFilmProfileName = (TextView) itemView.findViewById(R.id.row_suggestFilmProfileName);
row_suggestedLay = (RelativeLayout) itemView.findViewById(R.id.row_suggestedLay);
}
}
}
Model class :
public class SuggestFilmAddUser {
private int id;
private String name;
private String image;
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 getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
How can I it? Please help me
Inside onSend() , you need to add each objects to an arraylist which should be declared globally. Then call notifyItemInserted(arraylist.size()-1) in adapter to refresh recyclerview
public class SuggestFilmActivity ....
{ ArrayList<SuggestFilmAddUser> suggestFilmAddUserList=new ArrayList();
SuggestFilmUserAdapter suggestFilmUserAdapter;
......
......
protected void onCreate(Bundle savedInstance)
{....
....
....
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context,
suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
.....
.....
}
public void onSend(int Id, String name, String image) {
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
suggestFilmUserAdapter.notifyItemInserted(suggestFilmAddUserList.size()-1)
}
ArrayList.size() showing zero every time. Actually im trying to Filter the Data using the data stored on the ArrayList
This is my HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG_check="check";
public RecyclerView recyclerView;
SearchView realsv;
private AlbumsAdapter adapter;
private ArrayList<Album> albumList;
private ArrayList<Album> test;
private Album album;
public ImageView imga;
public CollapsingToolbarLayout collapsingToolbar;
public AppBarLayout appBarLayout;
ProgressDialog pd;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
realsv=(SearchView)rootView.findViewById(R.id.realsv);
recyclerView = (RecyclerView) rootView.findViewById(R.id.rcv);
//test.addAll(albumList);
//test.clear();
realsv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("YES","FIRST STEP"+albumList.size());
newText=newText.toLowerCase();
for(Album al: albumList)
{
String title = al.getName().toLowerCase();
ArrayList<Album> test = new ArrayList<>();
Log.i("CHEK",title);
if(title.contains(newText)){
Log.i("CHEK ok",title+"ok");
test.add(al);
}
}
adapter.setFilter(test);
// adapter.getFilter().filter(newText);
return true;
}
});
initViews();
return rootView;
}
private void initViews(){
pd = new ProgressDialog(getActivity());
pd.setMessage("Fetching Data...");
pd.setCancelable(false);
pd.show();
albumList = new ArrayList<>();
adapter = new AlbumsAdapter(getActivity(), albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
loadJSON();
}
private void loadJSON(){
try{
Client Client = new Client();
//this is where it all changes
Hindi apiService = Client.getClient().create(Hindi.class);
Call<AlbumsResponse> call = apiService.getAlbums();
call.enqueue(new Callback<AlbumsResponse>() {
#Override
public void onResponse(Call<AlbumsResponse> call, Response<AlbumsResponse> response) {
ArrayList<Album> items = response.body().getAlbums();
recyclerView.setAdapter(new AlbumsAdapter(getActivity(), items));
recyclerView.smoothScrollToPosition(0);
pd.hide();
}
#Override
public void onFailure(Call<AlbumsResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
// Toast.makeText(MainActivity.this, "Error Fetching Data!", Toast.LENGTH_SHORT).show();
pd.hide();
}
});
}catch (Exception e){
Log.d("Error", e.getMessage());
// Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
This is My adapter Class for Recyclerview
public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder>{
private Context mContext;
private ArrayList<Album> albumList;
//private List<Album> newList;
public AlbumsAdapter(Context mContext, ArrayList<Album> albuList) {
this.mContext = mContext;
this.albumList = albuList;
// this.newList=albuList;
}
#Override
public AlbumsAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.album_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final AlbumsAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(albumList.get(i).getName());
viewHolder.count.setText(albumList.get(i).getLang());
//load album cover using picasso
Picasso.with(mContext)
.load(albumList.get(i).getThumbnail())
.placeholder(R.drawable.load)
.into(viewHolder.thumbnail);
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_album, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
public void setFilter(ArrayList<Album> nn){
albumList= new ArrayList<Album>();
for (Album al:nn){
albumList.add(al);
}
notifyDataSetChanged();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_play_next:
Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
return albumList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
// overflow = (ImageView) view.findViewById(R.id.overflow);
//on item click
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Album clickedDataItem = albumList.get(pos);
Intent intent = new Intent(mContext, Det.class);
intent.putExtra("name", albumList.get(pos).getName());
intent.putExtra("lang", albumList.get(pos).getLang());
intent.putExtra("thumbnail", albumList.get(pos).getThumbnail());
intent.putExtra("scrn",albumList.get(pos).getScrn());
intent.putExtra("ourl",albumList.get(pos).getOurl());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
`
This is Model Class Album.java
public class Album {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lang")
#Expose
private String lang;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("scrn")
#Expose
private String scrn;
#SerializedName("ourl")
#Expose
private String ourl;
public Album() {
}
public Album(String name, String lang, String thumbnail, String scrn,
String ourl) {
this.name = name;
this.lang = lang;
this.thumbnail = thumbnail;
this.scrn=scrn;
this.ourl=ourl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getScrn() {
return scrn;
}
public void setScrn(String scrn) {
this.scrn = scrn;
}
public String getOurl() {
return ourl;
}
public void setOurl(String ourl) {
this.ourl = ourl;
}
}
This is the AlbumResponse.java
public class AlbumsResponse {
#SerializedName("Album")
#Expose
private ArrayList<Album> albums;
public ArrayList<Album> getAlbums(){
return albums;
}
public void setAlbums(ArrayList<Album>albums){
this.albums = albums;
}
}
Ok so in your LoadJson method, you populate a new array called items and then populate your adapter with it. So in your adapter your albumList gets populated which is fine. But then in your OnQueryTextChanged method you check for your query string in albumList array, which you have declared in your Home fragment but never initialized. So hence no filter results. assign your items to albumlist and it will work
In your loadJson() method, in onResponse you are creating a new ArrayList to get all albums and not setting that to your global variable albumList.
So you should do this,
ArrayList<Album> items = response.body().getAlbums();
albumList.addAll(items);
1- MainActivity:
public class MainActivity extends AppCompatActivity {
private List<String> mListItems = Arrays.asList("Hamaki","Amr Diab");
private ArtistsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.Artist_list_view);
mAdapter = new ArtistsAdapter(this, mListItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SoundActivity.class);
intent.putExtra("Artist", mListItems.get(position));
startActivity(intent);
}
});
}
}
2-Sound Activity:
public class SoundActivity extends AppCompatActivity {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new SoundFragment()).commit();
}
}
3-Sound Fragment:
public class SoundFragment extends Fragment {
static SCTrackAdapter mAdapter;
static DatabaseReference db;
static FirebaseHelper helper;
private TextView mSelectedTrackTitle;
static ArrayList<Music> mTracks = new ArrayList<>();
static MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
static String Artist;
static ListView listView;
int currentTrack;
private static String fileName;
public SoundFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
new Fetchtracks().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sound, container, false);
Intent intent = getActivity().getIntent();
if (intent != null) {
Artist = intent.getStringExtra("Artist");
}
listView = (ListView) rootView.findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(getActivity(), mTracks);
listView.setAdapter(mAdapter);
return rootView;
}
4- STrack Adapter:
public class SCTrackAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Music> mTracks;
public SCTrackAdapter(Context context, ArrayList<Music> tracks) {
mContext = context;
mTracks = tracks;
}
public void update_tracks(ArrayList<Music> list)
{
mTracks.clear();
mTracks.addAll(list);
}
#Override
public int getCount() {
return mTracks.size();
}
#Override
public Music getItem(int position) {
return mTracks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.track_list_row, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.track_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTextView.setText(mTracks.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView titleTextView;
}
}
5- Fetchtracks:
public class Fetchtracks extends AsyncTask<Void, Void, ArrayList<Music>> {
#Override
protected ArrayList<Music> doInBackground(Void... voids) {
db = FirebaseDatabase.getInstance().getReference().child(Artist);
helper = new FirebaseHelper(db);
mTracks.addAll(helper.retrieve());
Log.e("doInBackground: ",helper.retrieve()+"");
return mTracks;
}
#Override
protected void onPostExecute(ArrayList<Music> list) {
super.onPostExecute(list);
Log.e("doInBackground: ",list.size()+"");
mAdapter.update_tracks(list);
mAdapter.notifyDataSetChanged();
}
}
6- FirebaseHelper:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Music> A = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE
public Boolean save(Music m)
{
if(m==null)
{
saved=false;
}else
{
try
{
// db.child(Artist).push().setValue(m);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<Music> retrieve()
{
A.clear();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "1");
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "2");
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Log.e("onChildAdded: ", "3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Log.e("onChildAdded: ", "4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e("onChildAdded: ", "5");
}
});
return A;
}
private void fetchData(DataSnapshot dataSnapshot)
{
Music m=new Music();
m.setName(dataSnapshot.child("name").getValue().toString());
m.setUrl(dataSnapshot.child("url").getValue().toString());
A.add(m);
// SoundFragment.mTracks.add(m);
// Log.e("onFetch: ", SoundFragment.mTracks.size()+"");
}
}
7- Music:
public class Music {
String name;
String url;
public Music() {
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public String getURL() {
return url;
}
}
no need to call this in onPostExecute() as it is only set
listView.setAdapter(mAdapter);
The data is being fetched in the fetchData() method in FirebaseHelper, but isn't actually being stored in the variables petInfo and imgURL in the CardViewAdapter. This results in no cards showing in the RecyclerView fragment. When the app initializes, the dataset is 0, runs through the fetchData and the dataset is the size of items but leaves petInfo and imgURL null.
FirebaseHelper:
public class FirebaseHelper {
private DatabaseReference mDatabase;
Boolean saved = null;
ArrayList<AnimalType> animal = new ArrayList<>();
public FirebaseHelper(DatabaseReference mDatabase) {
this.mDatabase = mDatabase;
}
//Save
public Boolean save (AnimalType animalType){
if (animalType==null){
saved = false;
}
else{
try{
mDatabase.child("AnimalType").push().setValue(animalType);
saved=true;
}catch (DatabaseException e){
e.printStackTrace();
saved=false;
}
}
return saved;
}
//Read
public ArrayList<AnimalType> retrieve(){
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
Log.i(TAG, "onChildAdded");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
Log.i(TAG, "onChildChanged");
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return animal;
}
private void fetchData (DataSnapshot dataSnapshot){
animal.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
AnimalType animalType = new AnimalType();
animalType.setPetInfo(ds.getValue(AnimalType.class).getPetInfo());
animalType.setImgURL(ds.getValue(AnimalType.class).getImgURL());
animal.add(animalType);
}
}
}
Adapter:
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
Context mContext;
private List<AnimalType> mAnimalData = new ArrayList<>();
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView petInfo;
public ImageView imgURL;
public ViewHolder(View view){
super(view);
imgURL = (ImageView) view.findViewById(R.id.pet_image);
petInfo = (TextView) view.findViewById(R.id.pet_description);
}
}
//constructor
public CardViewAdapter(Context mContext, List<AnimalType> mAnimalData){
this.mAnimalData = mAnimalData;
}
//create new views
#Override
public CardViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
mContext = parent.getContext();
return viewHolder;
}
//replace contents of view
#Override
public void onBindViewHolder(ViewHolder holder, int position){
holder.petInfo.setText(mAnimalData.get(position).getPetInfo());
PicassoClient.downloadImage(mContext,mAnimalData.get(position).getImgURL(), holder.imgURL);
}
//return size of dataset
public int getItemCount(){
return mAnimalData.size();
}
}
Fragment:
public class DogFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mCardAdapter;
private RecyclerView.LayoutManager mCardLayoutManager;
DatabaseReference mDatabaseReference;
FirebaseHelper helper;
public static DogFragment newInstance(int page) {
DogFragment dogFragment = new DogFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
dogFragment.setArguments(args);
return dogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dog, container, false);
//cardview
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.card_view);
//setup firebase
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
helper= new FirebaseHelper(mDatabaseReference);
//create adapter class
//mCardAdapter = new CardViewAdapter(mAimalTypeList);
mCardAdapter = new CardViewAdapter(getActivity().getApplicationContext(), helper.retrieve());
mRecyclerView.setAdapter(mCardAdapter);
//add linear layout manager
mCardLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mCardLayoutManager);
//preparePetData();
return rootView;
}
}
Picasso:
public class PicassoClient {
public static void downloadImage(Context context, String url, ImageView img){
if(url != null && url.length()>0){
Picasso.with(context).load(url).placeholder(R.drawable.placeholder).into(img);
}
else {
Picasso.with(context).load(R.drawable.placeholder).into(img);
}
}
}
Your call to helper.retrieve() is kicking off mDatabase.addChildEventListener the results of which will come back asynchronously....in the meantime you're returning empty list from that method (default value of animal). You need to update adapter when results come back (after you've called fetchData(dataSnapshot);)