I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});
Related
I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.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) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}
I am looking some help for my application. I've built an app and i've included a chat feature. Within the chat fragment I have 2 additional fragments, one for chats currently open and one for all users which can be messaged. I want to incorroprate a search bar into each of these fragements to allow the user to find a certain user to message. I am
users fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gold"
tools:context=".ChatFragments.UsersFragment">
<EditText
android:id="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#android:color/white"
android:ems="20"
android:hint="#string/search"
android:layout_weight="0.5"
android:paddingLeft="15dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_below="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
users fragment java class
package com.alicearmstrong.coffeysloyaltyprojectv1.ChatFragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import com.alicearmstrong.coffeysloyaltyprojectv1.Adapter.CustomerAdapter;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.List;
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private CustomerAdapter customerAdapter;
private List<Customers> customersList;
DatabaseReference databaseReference;
EditText etSearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_users , container, false);
etSearch = view.findViewById(R.id.etSearch);
recyclerView = view.findViewById( R.id.recycler_view );
recyclerView.setHasFixedSize( true );
recyclerView.setLayoutManager( new LinearLayoutManager( getContext() ) );
customersList = new ArrayList<>( );
readCustomers();
return view;
}
// Method for reading customers
private void readCustomers()
{
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Customers");
databaseReference.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
customersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Customers customers = snapshot.getValue(Customers.class);
if (!customers.getId().equals(firebaseUser.getUid()))
{
customersList.add( customers );
}
}
customerAdapter = new CustomerAdapter( getContext(), customersList );
recyclerView.setAdapter( customerAdapter );
}
#Override
public void onCancelled( #NonNull DatabaseError databaseError) {
}
} );
}
}
customerAdapter.java
package com.alicearmstrong.coffeysloyaltyprojectv1.Adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.alicearmstrong.coffeysloyaltyprojectv1.uiOwner.chatOwner.MessageActivityOwner;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import java.util.ArrayList;
import java.util.List;
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder>
{
private Context context;
private List<Customers> customersList;
public CustomerAdapter (Context context, List<Customers> customersList)
{
this.customersList = customersList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
// Set layout to user_item for displaying each user
View view = LayoutInflater.from(context).inflate( R.layout.user_item , viewGroup, false);
return new CustomerAdapter.ViewHolder( view );
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i)
{
final Customers customer = customersList.get( i );
// Set title to user's name
viewHolder.customerName.setText( customer.getFirstName() + " " + customer.getSurname() );
// Open Message Activity when user is selected
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(context, MessageActivityOwner.class );
intent.putExtra( "userid", customer.getId() );
context.startActivity( intent );
}
} );
}
#Override
public int getItemCount()
{
return customersList.size();
}
/* #Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Customers> filteredList = new ArrayList<>( );
if (constraint == null || constraint.length() == 0)
{
filteredList.addAll( customersList );
}
else
{
// allows search to be case sensitive
String filteredPattern = constraint.toString().toLowerCase().trim();
for(Customers customers : customersList )
{
}
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView customerName;
public ViewHolder(#NonNull View view)
{
super( view );
customerName = view.findViewById( R.id.customerName );
}
}
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
}
customers database
package com.alicearmstrong.coffeysloyaltyprojectv1.database;
public class Customers
{
String id, firstName,surname, DOB, contactNumber, email, qrCode;
Integer loyaltyScore;
public Customers(String id, String firstName, String surname, String DOB, String contactNumber, String email, String qrCode, Integer loyaltyScore)
{
this.id = id;
this.firstName = firstName;
this.surname = surname;
this.DOB = DOB;
this.contactNumber = contactNumber;
this.email = email;
this.qrCode = qrCode;
this.loyaltyScore = loyaltyScore;
}
public String getId() {
return id;
}
public String getFirstName()
{
return firstName;
}
public String getSurname()
{
return surname;
}
public String getDOB()
{
return DOB;
}
public String getContactNumber()
{
return contactNumber;
}
public String getEmail()
{
return email;
}
public String getQrCode()
{
return qrCode;
}
public Integer getLoyaltyScore()
{
return loyaltyScore;
}
public Customers()
{
}
}
I read in to the addTextChangeListener method just not sure how to implement the method. Any help would be greatly appreciated.
why using textView when searchView is exsist. check this code below but let me see ur Customers java class then i can help u better. at the first set search view then find view by id it then ....
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
List<Customers> newList = new ArrayList<>();
for (Customers customersList : accounts) {
if (customersList.customerName.toLowerCase().contains(userInput)) {
newList.add(accountList);
}
}
accountAdapter.upToDate(newList);
return true;
}
});
then add upToDate function in ur adapter and call it at the above code.
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
I know there is lots of threads talk about first item problems in viewpager, I searched many time about my issue but no way I just lose time.
would you help me, please ?
I use FragmentStatePagerAdapter , fragment and loader manager that add radio buttons dynamically. the first iitem in view pager doesn't show radio buttons until I swipe to third item and back again to the first one.
screen
Image
Fragment:
package mohalim.android.egybankstest.Fragments;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import mohalim.android.egybankstest.Database.AppContract;
import mohalim.android.egybankstest.Models.Choice;
import mohalim.android.egybankstest.Models.Question;
import mohalim.android.egybankstest.R;
import mohalim.android.egybankstest.ResultActivity;
public class QuizFragement extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String UPDATE = "update";
private static final int GET_CHOICES_LOADER_ID = 100;
private static final int UPDATE_CHOSEN_ANSWER_LOADER_ID = 101;
private static final String SELECTED_QUIZ = "selected_quiz";
ArrayList<Question> questions;
ArrayList<Choice> choices;
int questionPosition;
String selectedQuiz;
RadioGroup radioGroup;
TextView questionText;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
choices = new ArrayList<>();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.quiz_fragment, container, false);
questionText = view.findViewById(R.id.m);
radioGroup = view.findViewById(R.id.choices_radio);
radioGroup.removeAllViews();
questionText.setText(questions.get(questionPosition).getQuestion_text());
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}
/**
* end the session
*/
FloatingActionButton fab = view.findViewById(R.id.end_session);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ResultActivity.class);
intent.putExtra(SELECTED_QUIZ,selectedQuiz);
startActivity(intent);
getActivity().finish();
}
});
return view;
}
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable final Bundle args) {
if (id==GET_CHOICES_LOADER_ID){
Uri choicesUri = AppContract.ChoiceEntry.CONTENT_URI
.buildUpon()
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId()))
.build();
String questionId = String.valueOf(questions.get(questionPosition).getQuestionId());
String questionIDSelection = AppContract.ChoiceEntry.COLUMN_QUESTION_ID + "=?";
String[] questionIDSelectionArgs = new String[]{questionId};
return new CursorLoader(
getActivity(),
choicesUri,
null,
questionIDSelection,
questionIDSelectionArgs,
null
);
}else if(id == UPDATE_CHOSEN_ANSWER_LOADER_ID){
return new AsyncTaskLoader<Cursor>(getActivity()) {
#Nullable
#Override
public Cursor loadInBackground() {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Uri updateChosenUri = AppContract.QuestionsEntry.CONTENT_URI
.buildUpon()
.appendPath(UPDATE)
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build();
ContentValues contentValues = new ContentValues();
contentValues.put(AppContract.QuestionsEntry.COLUMN_ANSWER_CHOSEN,checkedId);
if (group.getChildAt(checkedId-1).getTag().toString().equals("1")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 1);
}else if (group.getChildAt(checkedId-1).getTag().toString().equals("0")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 0);
}
getActivity().getContentResolver().update(updateChosenUri,contentValues,null,null);
Cursor cursor = getActivity().getContentResolver().query(
AppContract.QuestionsEntry.CONTENT_URI.buildUpon().appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build(),
null,null,null,null
);
if (cursor.getCount() == 1){
cursor.moveToFirst();
Log.v("string", cursor.getInt(cursor.getColumnIndex(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT))+"");
Log.v("string 2", group.getChildAt(radioGroup.getCheckedRadioButtonId()-1).getTag().toString());
}
}
});
return null;
}
};
}
return null;
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor choicesCursor) {
if (questionPosition == 0){
Toast.makeText(getActivity(), ""+selectedQuiz, Toast.LENGTH_SHORT).show();
}
if (loader.getId() == GET_CHOICES_LOADER_ID){
if (choicesCursor.getCount() >0){
while (choicesCursor.moveToNext()){
String text = choicesCursor.getString(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_CHOICE_TEXT));
int is_correct = choicesCursor.getInt(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_IS_TRUE));
Choice choice = new Choice();
choice.setChoiceText(text);
choice.setCorrect(is_correct);
choices.add(choice);
}
for (int i=0; i<choices.size();i++){
LayoutInflater inflater = LayoutInflater.from(getContext());
final View radioButton = inflater.inflate(R.layout.radio_button,radioGroup,false);
((RadioButton) radioButton).setText(choices.get(i).getChoiceText());
radioButton.setTag(choices.get(i).isCorrect());
radioGroup.addView(radioButton);
}
for (int i = 0; i<radioGroup.getChildCount();i++){
radioGroup.getChildAt(i).setId(i+1);
}
}
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}
}
}
#Override
public void onLoaderReset(#NonNull Loader<Cursor> loader) {
}
public void setQuestions(ArrayList<Question> questions) {
this.questions = questions;
}
public void setQuestionPosition(int questionPosition) {
this.questionPosition = questionPosition;
}
public ArrayList<Question> getQuestions() {
return questions;
}
public int getQuestionPosition() {
return questionPosition;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
}
ViewPagerAdapter
package mohalim.android.egybankstest.Adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import mohalim.android.egybankstest.Fragments.QuizFragement;
import mohalim.android.egybankstest.Models.Question;
public class MyQuizPager extends FragmentStatePagerAdapter {
ArrayList<Question> questions;
String selectedQuiz;
public MyQuizPager(FragmentManager fm, ArrayList<Question> questions, String selectedQuiz) {
super(fm);
this.questions = questions;
this.selectedQuiz = selectedQuiz;
}
#Override
public Fragment getItem(int position) {
QuizFragement fragment = new QuizFragement();
fragment.setQuestions(questions);
fragment.setQuestionPosition(position);
fragment.setSelectedQuiz(selectedQuiz);
return fragment;
}
#Override
public int getCount() {
return questions.size();
}
#Override
public int getItemPosition(Object object) {
QuizFragement fragment = (QuizFragement) object;
int position = fragment.getQuestionPosition();
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
}
All code is here
Finnaly I found the solution:
Quate:
By default it is viewpager.setOffscreenPageLimit(1) , meaning View
pager will by default load atleast 1 on the right and one on the left
tab of current tab.
https://stackoverflow.com/a/47054077/5862361
when i start quizActivity viewpager load the first item and the second too so the loadermanager restart before complete its work.
I solved it by adding another loadermanger
one for the first item and the second for the second one:
if (questionPosition == 0){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}else{
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}
}else if (questionPosition == 1){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
Can anyone help me with this firebase recycler view using fragments issue? I am having a problem with retrieving the data from firebase to my recycler view. I am using fragments and the app crashes everytime I run it.
Here's my code:
SubjecList.java
package com.google.myeclassrecordapp.mye_classrecord;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.w3c.dom.Text;
public class SubjectsList extends Fragment {
private View view;
private Context c;
private RecyclerView myTimeline;
private FirebaseDatabase databaseReference;
private DatabaseReference mFireDatabasaeRef;
private LinearLayoutManager mananger;
private RecyclerView mRecyclerView;
FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.schedule_model, container, false);
mFireDatabasaeRef = FirebaseDatabase.getInstance().getReference().child("SubjectsList");
c = getContext();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rcsched);
mananger = new LinearLayoutManager(c);
mRecyclerView.setHasFixedSize(true);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder>(
ScheduleListAdapter.class,
R.layout.schedule_model,
ViewHolder.class,
mFireDatabasaeRef
)
{
#Override
protected void populateViewHolder(ViewHolder viewHolder, ScheduleListAdapter model, int position) {
viewHolder.setSubjectCode(model.getSubjectCode());
viewHolder.setSection(model.getSection());
viewHolder.setTime(model.getTime());
viewHolder.setDay(model.getDay());
viewHolder.setRoom(model.getRoom());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.notifyDataSetChanged();
//mRecyclerView.setLayoutManager(mananger);
return view;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setSubjectCode(String subjectcode){
TextView txtSubjectCode = (TextView) itemView.findViewById(R.id.txtsubjectcode);
txtSubjectCode.setText(subjectcode);
}
public void setSection(String section){
TextView txtSection = (TextView) itemView.findViewById(R.id.txtsection);
txtSection.setText(section);
}
public void setTime(String time){
TextView txtTime = (TextView) itemView.findViewById(R.id.txttime);
txtTime.setText(time);
}
public void setDay(String day){
TextView txtDay = (TextView) itemView.findViewById(R.id.txtday);
txtDay.setText(day);
}
public void setRoom(String room){
TextView txtRoom = (TextView) itemView.findViewById(R.id.txtroom);
txtRoom.setText(room);
}
}
}
ScheduleListAdapater.java
package com.google.myeclassrecordapp.mye_classrecord;
/**
* Created by Pau-Le on 5/12/17.
*/
public class ScheduleListAdapter {
private String SubjectCode;
private String Section;
private String Time;
private String Day;
private String Room;
public ScheduleListAdapter() {
}
public ScheduleListAdapter(String subjectCode, String section, String time, String day, String room) {
SubjectCode = subjectCode;
Section = section;
Time = time;
Day = day;
Room = room;
}
public String getSubjectCode() {
return SubjectCode;
}
public void setSubjectCode(String subjectCode) {
SubjectCode = subjectCode;
}
public String getSection() {
return Section;
}
public void setSection(String section) {
Section = section;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getDay() {
return Day;
}
public void setDay(String day) {
Day = day;
}
public String getRoom() {
return Room;
}
public void setRoom(String room) {
Room = room;
}
}
Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
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.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.