I wanna check my adapter before adding new item and if there is a duplicate item then ignore it.I tried this method but didn't work for me.
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.Tshirt:
radio="Tshirt";
break;
case R.id.Shoes:
radio="Shoes";
break;
default:
radio="Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty() )
list.add(new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop));
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
}
});
You can simply check whether your list contains a certain String and / or object already.
if(!list.contains(...) {
list.add(..);
}
You can check this thread for more information:
Check if a String is in an ArrayList of Strings
If order is not important , then you could use HashSet instead of a list, a type of SET, these are the collections that do not allow duplicate values but do not preserve insertion order too.
Java HashSet
Example usage:-
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Here is my code:
Mainactivity.java
package com.example.esi.shopapp;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView lstCountries;
public Button btnadd;
private EditText txtname;
private EditText txtdes;
private RadioGroup radioGroup;
String radio = "";
private List<products> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstCountries = (ListView) findViewById(R.id.lists);
btnadd = findViewById(R.id.button);
txtname =findViewById(R.id.txt_name);
txtdes =findViewById(R.id.txt_desc);
radioGroup = findViewById(R.id.categorize);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.Tshirt:
radio="Tshirt";
break;
case R.id.Shoes:
radio="Shoes";
break;
default:
radio="Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty() )
if (!list.contains(txtname.getText().toString()))
list.add(new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop));
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.clear_form:
txtname.setText("");
txtdes.setText("");
break;
case R.id.clear_list:
lstCountries.setAdapter(null);
break;
case R.id.setting:
break;
case R.id.exit:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure to exit?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
}
return super.onOptionsItemSelected(item);
}
}
myadapter.java
package com.example.esi.shopapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class myadapter extends BaseAdapter {
private Context context;
private List<products> list;
public myadapter(Context context, List<products> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup root) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_layout, root, false);
}
TextView txtCountryName = convertView.findViewById(R.id.txt_product_name);
TextView txtCountryContinent = convertView.findViewById(R.id.txt_product_desc);
TextView txtype = convertView.findViewById(R.id.txt_product_type);
ImageView imgCountryFlag = convertView.findViewById(R.id.img_country_flag);
txtCountryName.setText(list.get(position).getName());
txtCountryContinent.setText(list.get(position).getDescribe());
txtype.setText(list.get(position).getType());
imgCountryFlag.setImageResource(list.get(position).getFlag());
return convertView;
}
}
products.java
package com.example.esi.shopapp;
public class products {
private String name;
private String describe;
private String type;
private int flag;
public products(String name, String describe, String type, int flag) {
this.name = name;
this.describe = describe;
this.type = type;
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Your logic is wrong. You are creating a new instance of the adapter in each item click. You should move
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
to the onCreate method. Make adapter a global variable and
change your current code to this.
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.Tshirt:
radio = "Tshirt";
break;
case R.id.Shoes:
radio = "Shoes";
break;
default:
radio = "Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty()) {
products product = new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop)
if (!list.contains(product)) {
list.add(product);
adapter.notifyDataSetChanged();
}
}
}
});
Related
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;
}
}
});
I have a ListView fragment that has the option to save specific table values. You can click a button to toggle the table to only show saved values. When the toggle is active instead of saving you have the option to delete values. I have noticed however that while the delete will delete the value permanently so long as the app is open, If i close the app and reopen it, the value will reappear. Also if I delete the app and reinstall this same value reappears. I'm not sure how this value is getting added in and why it refuses to go. Debugging shows me saving the correct values in SharedPreferences but that does not stay.
EDIT: After some more testing it appears that the first item saved in the specific SharedPreferences remains permanently saved. It cannot be removed and all other values saved will not remain there.
Fragment:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.os.StrictMode;
import com.tble.brgo.HTMLPull;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Websites#newInstance} factory method to
* create an instance of this fragment.
*/
public class Websites extends Fragment implements SearchView.OnQueryTextListener, displayInterface {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private SearchView mSearchView;
private ListView mListView;
public Boolean toggle = false;
public ArrayList<InfoArticle> mData = new ArrayList<InfoArticle>();
public StandardCellAdapter mAdapter;
public ArrayList<InfoArticle> fDataSet = new ArrayList<InfoArticle>();
public Websites webTable;
public Websites() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Websites.
*/
// TODO: Rename and change types and number of parameters
public static Websites newInstance() {
Websites fragment = new Websites();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toggle = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_websites, container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<InfoArticle> data = new ArrayList<InfoArticle>();
webTable = this;
try {
data = getData();
} catch (IOException e) {
e.printStackTrace();
}
mListView = (ListView) view.findViewById(R.id.WebsiteTable);
final StandardCellAdapter adapter = new StandardCellAdapter(getActivity(), data, 1,this);
fDataSet = data;
mData = data;
mListView.setAdapter(adapter);
mAdapter = adapter;
mSearchView = (SearchView) view.findViewById(R.id.searchView);
mListView.setTextFilterEnabled(true);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.dataToggle);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleView();
}
});
setupSearchView();
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.webRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
mData = getData();
mAdapter = new StandardCellAdapter(getContext(), mData, 1,webTable);
mListView.setAdapter(mAdapter);
} catch (IOException e) {
e.printStackTrace();
}
swipeLayout.setRefreshing(false);
}
});
return view;
}
private void setupSearchView() {
mSearchView.setOnQueryTextListener(this);
mSearchView.setIconifiedByDefault(true);
}
private ArrayList<InfoArticle> getData() throws IOException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
int school = sharedPref.getInt("School", 14273);
HTMLPull Connection = new HTMLPull();
Connection.getStaff(school);
Connection.Results.remove(0);
return Connection.Results;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public ArrayList<InfoArticle> toData(ArrayList<String> t, ArrayList<String> d) {
ArrayList<InfoArticle> temp = new ArrayList<InfoArticle>();
if (t.size() == 0) {
temp.add(new InfoArticle("Slide to Save Teachers", "google.com"));
} else {
for (int i = 0; i < t.size(); i++) {
temp.add(new InfoArticle(t.get(i), d.get(i)));
}
}
return temp;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private void toggleView(){
if (!toggle) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
HashSet<String> defv = new HashSet<String>();
ArrayList<String> teachers = new ArrayList<String>(sharedPref.getStringSet("teachPref", defv));
ArrayList<String> links = new ArrayList<String>(sharedPref.getStringSet("linkPref", defv));
mAdapter = new StandardCellAdapter(getContext(), toData(teachers, links),2,this);
mListView.setAdapter(mAdapter);
toggle = true;
} else {
mAdapter = new StandardCellAdapter(getContext(), mData, 1,this);
mListView.setAdapter(mAdapter);
toggle = false;
}
}
/**public void displayWebpage(int position){
if (toggle == true) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(mAdapter.getItem(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
} else {
if (!mSearchView.isIconified()) {
for (InfoArticle a : fDataSet) {
if (a.title.equals(((InfoArticle) mListView.getAdapter().getItem(position)).title)) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(a.description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
} else {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(fDataSet.get(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
}*/
public void displayWebpage(String Link){
WebsiteDisplay fullView = WebsiteDisplay.newInstance(Link);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
CellAdapter:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.nfc.Tag;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.graphics.Typeface;
import android.widget.Filterable;
import android.widget.Filter;
import org.w3c.dom.Text;
/**
* Created by Praveen on 8/21/16.
*/
public class StandardCellAdapter extends ArrayAdapter<InfoArticle> implements Filterable {
public ArrayList<InfoArticle> orig;
public ArrayList<InfoArticle> Teachers;
public SwipeRevealLayout swipeV;
public TextView deleteButton;
public TextView saveButton;
public int tableType;
public displayInterface activity;
public Context ct;
public StandardCellAdapter(Context context, ArrayList<InfoArticle> titles, int tableType, displayInterface inter) {
super(context, 0, titles);
this.Teachers = titles;
this.tableType = tableType;
saveButton = new TextView(context);
deleteButton = new TextView(context);
activity = inter;
ct = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String title = getItem(position).title;
String desc = getItem(position).description;
Holder TagHolder = null;
TextView Ctitle;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
if (tableType == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.nclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
else if(tableType == 1){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.scSwipe);
saveButton = (TextView)convertView.findViewById(R.id.saveButton);
TagHolder.Save = saveButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.tcSwipe);
deleteButton = (TextView) convertView.findViewById(R.id.deleteButton);
TagHolder.Delete = deleteButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
}
else {
TagHolder = (Holder) convertView.getTag();
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
if(tableType == 1) {
TagHolder.Save.setTag(position);
TagHolder.Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTeacher((int)v.getTag());
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
else if(tableType == 2) {
TagHolder.Delete.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteTeacher((int)v.getTag());
if(Teachers.size() == 0)
Teachers.add(new InfoArticle("Slide to Save Teachers", "google.com"));
notifyDataSetChanged();
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
Typeface customFont = Typeface.SERIF;
Ctitle.setTypeface(customFont);
Ctitle.setText(title);
return convertView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<InfoArticle> results = new ArrayList<InfoArticle>();
if (orig == null)
orig = Teachers;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final InfoArticle g : orig) {
if (g.title.toLowerCase()
.contains(constraint.toString().toLowerCase())) {
results.add(g);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Teachers = (ArrayList<InfoArticle>)results.values;
notifyDataSetChanged();
}
};
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public ArrayList<InfoArticle> toIA(ArrayList<String> data){
ArrayList<InfoArticle> converted = new ArrayList<InfoArticle>();
for(String a: data)
{
converted.add(new InfoArticle(a,""));
}
return converted;
}
#Override
public int getCount() {
return Teachers.size();
}
#Override
public InfoArticle getItem(int position) {
return Teachers.get(position);
}
public void saveTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
teach.add(Teachers.get(position).title);
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
link.add(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
new AlertDialog.Builder(getContext())
.setTitle("Teacher Saved")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(true);
}
private void deleteTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
teach.remove(Teachers.get(position).title);
link.remove(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
HashSet<String> defv = new HashSet<String>();
Teachers.remove(position);
new AlertDialog.Builder(getContext())
.setTitle("Teacher Deleted")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(false);
}
class Holder{
TextView Delete;
TextView Save;
TextView Cell;
}
}
I have an app that uses RecyclerView. When user selects "Add New Row" from the options menu, I output a test message to the screen, and some values get appended to two different ArrayLists. That part is working great, as I have confirmed these values are successfully added by looking at the ArrayList values using the debugger.
Anyhow I am not able to get the RecyclerView to redraw the screen and show the new information. My attempt to redraw / update the screen is by using this code (line 78 of MainActivity.java):
//call notify data set changed method for the adapter
adapter.notifyDataSetChanged();
Maybe I am not calling notifyDataSetChanged on the same adapter that actually is used for RecycleView??
Here is the complete code for MainActivity.java (see options menu code at end):
package com.joshbgold.ironmax;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int ADD_ROW = 1; //used for case statement statement to select menu item
private RecyclerView recyclerView;
public Exercises exercises = new Exercises();
public ExerciseRow adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
assert getSupportActionBar() != null;
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.barbell);
actionBar.setTitle(" " + "Iron Max");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//ExerciseRow adapter = new ExerciseRow(this);
adapter = new ExerciseRow(this);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_row, menu);
return super.onCreateOptionsMenu(menu);*/
menu.add(0, ADD_ROW, 0, "Add New Row");
menu.getItem(0).setIcon(R.drawable.plus);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setIcon(R.drawable.plus);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int length;
switch (item.getItemId()) {
case 1:
Toast msg = Toast.makeText(MainActivity.this, "Test code for adding an exercise", Toast.LENGTH_LONG);
msg.show();
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
length = exercises.getExercisesArrayLength();
//call notify data set changed method for the adapter
adapter.notifyItemInserted(length - 1);
adapter.notifyDataSetChanged();
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is Exercises.java:
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class Exercises extends AppCompatActivity {
public ArrayList<String> exercisesArrayList = new ArrayList<>(); //stores all the lifts
private ArrayList<Integer> personalBestsArrayList = new ArrayList<>(); //stores personal bests in pounds
public ArrayList<String> getExercisesArray() { //returns the whole exercises arraylist
return exercisesArrayList;
}
public ArrayList<Integer> getPersonalBests() { //returns the whole personal bests arraylist
return personalBestsArrayList;
}
public String getExercise(int position) { //returns individual exercise from array
return exercisesArrayList.get(position);
}
public void addExercise(String exercise) {
exercisesArrayList.add(exercise);
}
public void removeExercise(int position) {
exercisesArrayList.remove(position);
}
public void editExercise(int position, String exercise) {
exercisesArrayList.set(position, exercise);
}
public int getExercisesArrayLength() {
return exercisesArrayList.size();
}
public Integer getPersonalBest(int position) { //returns individual personal best from array
return personalBestsArrayList.get(position);
}
public void addPersonalBest(int personalBest) {
personalBestsArrayList.add(personalBest);
}
public void removePersonalBest(int position) {
personalBestsArrayList.remove(position);
}
public void editPersonalBest(int position, int personalBest) {
personalBestsArrayList.set(position, personalBest);
}
public Exercises() {} //constructor
}
Here is ExerciseRow.java:
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ExerciseRow extends RecyclerView.Adapter<ExerciseRow.ExerciseViewHolder> {
String exerciseName = "burpee";
String exercisePR = "100"; // user's personal record for this exercise in pounds
private Context context;
Exercises exercises = new Exercises();
public ExerciseRow(Context context) {
this.context = context;
}
#Override
public ExerciseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_list_item, parent, false);
return new ExerciseViewHolder(view);
}
#Override
public void onBindViewHolder(ExerciseViewHolder holder, int position) {
ArrayList<String> exercisesArray = exercises.getExercisesArray();
holder.bindExercises(exercisesArray.get(position));
}
#Override
public int getItemCount() {
return exercises.getExercisesArrayLength();
}
public class ExerciseViewHolder extends RecyclerView.ViewHolder {
public TextView exerciseNameTextView;
public TextView personalRecordTextView;
public ImageView edit_Icon;
public ImageView percentages_Icon;
public ImageView trash_Icon;
public ImageView plus_icon;
public ImageView facebook_icon;
public ImageView twitter_icon;
public ExerciseViewHolder(View itemView) {
super(itemView);
exerciseNameTextView = (TextView) itemView.findViewById(R.id.list_item_exercise_textview);
personalRecordTextView = (TextView) itemView.findViewById(R.id.list_item_amount_textview);
edit_Icon = (ImageView) itemView.findViewById(R.id.list_item_pencil);
percentages_Icon = (ImageView) itemView.findViewById(R.id.list_item_percent);
trash_Icon = (ImageView) itemView.findViewById(R.id.list_item_trash);
plus_icon = (ImageView) itemView.findViewById(R.id.list_item_plus);
facebook_icon = (ImageView) itemView.findViewById(R.id.list_item_facebook);
twitter_icon = (ImageView) itemView.findViewById(R.id.list_item_twitter);
View.OnClickListener plus = new View.OnClickListener() {
#Override
public void onClick(View view) {
// allow user to add a new exercise and personal best
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
notifyDataSetChanged();
}
};
View.OnClickListener edit = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be edited.", Toast.LENGTH_LONG).show();
}
else{
editRow(position); //edit the row at the current position
notifyDataSetChanged();
}
}
};
View.OnClickListener percentages = new View.OnClickListener() {
#Override
public void onClick(View view) {
//get exercise name
exerciseName = exerciseNameTextView.getText().toString();
exercisePR = personalRecordTextView.getText().toString();
//show percentages layout
startPercentagesActivity(exerciseName, exercisePR);
}
};
View.OnClickListener trash = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be deleted.", Toast.LENGTH_LONG).show();
} else {
exercises.removeExercise(position);
exercises.removePersonalBest(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, exercises.getExercisesArrayLength());
}
}
};
plus_icon.setOnClickListener(plus);
edit_Icon.setOnClickListener(edit);
percentages_Icon.setOnClickListener(percentages);
trash_Icon.setOnClickListener(trash);
}
public void bindExercises(String exercises) {
Exercises exercisesObject = new Exercises();
exerciseNameTextView.setText(exercisesObject.getExercise(getAdapterPosition()));
personalRecordTextView.setText((exercisesObject.getPersonalBest(getAdapterPosition())).toString() + " pounds");
}
}
private void startPercentagesActivity(String some_exercise, String personal_record) {
Intent intent = new Intent(context, PercentagesActivity.class);
intent.putExtra("exerciseName", some_exercise);
intent.putExtra("personalRecord", personal_record);
context.startActivity(intent);
}
protected void editRow(final int position) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final View textEntryView = layoutInflater.inflate(R.layout.text_entry, null);
final EditText liftName = (EditText) textEntryView.findViewById(R.id.liftNameEditText);
final EditText PersonalBestInPounds = (EditText) textEntryView.findViewById(R.id.personalBestEditText);
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setIcon(R.mipmap.barbell)
.setTitle("Please make your changes:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve the user's input
String lift = liftName.getText().toString();
int personalBest = Integer.parseInt(PersonalBestInPounds.getText().toString());
//save the user's input to the appropriate arrays
exercises.editExercise(position, lift);
exercises.editPersonalBest(position, personalBest);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
}
If you have read this far, I give you credit! Please understand I am completely new to RecyclerView, so whatever error(s) I have made could be something quite simple even.
The issue is that you have two different instances of ExercisesOne in MainActivity and another in ExerciseRow You are adding the data to the wrong one.
A few other things that may help you along your way.
Exercises Should not extend AppCompatActivity (or really anything as far as I can tell)
You should avoid saving a reference to the context (as you are doing in Exercises) it can great memory issues. Instead try one of the following.
A. Use the context to get the LayoutInflater in the constructor
B. Call parent.getContext() in onCreateViewHolder
I am making a app with RecylerView populated with data form an online server. It has a custom layout with a favorite button that when clicked the icon changes.I have a problem trying to save state of a selected view on the RecyclerView. The RecyclerView does not save the selected state on scrolling back up. Kindly help.
Model Class
package com.smartdevelopers.kandie.nicedrawer.newsModel;
/**
* Created by 4331 on 25/09/2015.
*/
public class Latest {
public String excerpt;
public String articleImage;
public String articleUrl;
public boolean mfavourite;
public boolean isFavourite(){
return mfavourite;
}
public String getArticleUrl() {
return articleUrl;
}
public void setArticleUrl(String articleUrl) {
this.articleUrl = articleUrl;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getArticleImage() {
return articleImage;
}
public void setArticleImage(String articleImage) {
this.articleImage = articleImage;
}
}
Adapter
package com.smartdevelopers.kandie.nicedrawer.newsAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartdevelopers.kandie.nicedrawer.R;
import com.smartdevelopers.kandie.nicedrawer.ReadArticleActivity;
import com.smartdevelopers.kandie.nicedrawer.newsModel.Latest;
import com.smartdevelopers.kandie.nicedrawer.util.SharedPreferenceRecycler;
import java.util.HashMap;
import java.util.List;
/**
* Created by 4331 on 29/09/2015.
*/
public class OtherNewsAdapter extends RecyclerView.Adapter<OtherNewsAdapter.ViewHolder> {
private List<Latest> feedItemList;
private Context mContext;
private static final String TAG = "ActivityGplus";
SharedPreferenceRecycler sharedPreference = new SharedPreferenceRecycler();
public OtherNewsAdapter(Context context, List<Latest> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_other_news, null);
ViewHolder mh = new ViewHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final Latest feedItem = feedItemList.get(i);
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.placeholder)
.showImageOnFail(R.drawable.placeholder)
.showImageOnLoading(R.drawable.placeholder).build();
//download and display image from url
imageLoader.displayImage(feedItem.getArticleImage(), viewHolder.thumbnail, options);
// Glide.with(mContext).load(feedItem.getArticleImage())
// .error(R.drawable.placeholder)
// .placeholder(R.drawable.placeholder)
// .into(viewHolder.thumbnail);
viewHolder.title.setText(Html.fromHtml(feedItem.getExcerpt()));
viewHolder.articleUrl.setText(Html.fromHtml(feedItem.getArticleUrl()));
viewHolder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ReadArticleActivity.class);
intent.putExtra("articleUrl", viewHolder.articleUrl.getText().toString());
mContext.startActivity(intent);
}
});
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(feedItem)) {
viewHolder.favImage.setImageResource(R.drawable.heart_red);
viewHolder.favImage.setSelected(true);
viewHolder.favImage.setTag("red");
hashMap.get(i);
}
else {
viewHolder.favImage.setImageResource(R.drawable.heart_grey);
viewHolder.favImage.setSelected(false);
viewHolder.favImage.setTag("grey");
}
viewHolder.title.setTag(viewHolder);
viewHolder.thumbnail.setId(R.id.otherImage);
viewHolder.articleUrl.setTag(viewHolder);
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
OtherNewsRowHolder holder = (OtherNewsRowHolder) view.getTag();
int position = holder.getPosition();
Latest feedItem = feedItemList.get(position);
Toast.makeText(mContext, feedItem.getExcerpt(), Toast.LENGTH_SHORT).show();
}
};
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Latest checkProduct) {
boolean check = false;
List<Latest> favorites = sharedPreference.getFavorites(mContext);
if (favorites != null) {
for (Latest product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail, favImage;
protected TextView title,articleUrl;
public ViewHolder(View itemView) {
super(itemView);
this.thumbnail = (ImageView) itemView.findViewById(R.id.otherImage);
this.title = (TextView) itemView.findViewById(R.id.otherExcerpt);
this.articleUrl=(TextView)itemView.findViewById(R.id.otherUrl);
this.favImage = (ImageView) itemView.findViewById(R.id.imgbtn_favorite);
favImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String tag = favImage.getTag().toString();
if(!favImage.isSelected()) {
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(mContext, feedItemList.get(getItemCount() - 1));
// Toast.makeText(mContext, mContext.getResources().getString(R.string.add_favr),
// Toast.LENGTH_SHORT).show();
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.add_favr)
.textColor(Color.WHITE)
.color(Color.RED)
.duration(Snackbar.SnackbarDuration.LENGTH_SHORT));
//End of SnackBack
favImage.setTag("red");
favImage.setImageResource(R.drawable.heart_red);
}
}
else {
sharedPreference.removeFavorite(mContext, feedItemList.get(getItemCount() - 1));
favImage.setTag("grey");
favImage.setImageResource(R.drawable.heart_grey);
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.remove_favr)
.textColor(Color.WHITE)
.color(Color.RED) .duration(Snackbar.SnackbarDuration.LENGTH_SHORT).animation(false));
//End of SnackBack
}
}
}
}
I ran into this problem a couple of days ago - the reason is that you have not updated your feedItemList with the applicable changes. If you update the list by setting some of the member variables (like setExcerpt()) of the Latest class once it has change, your recyclerview will work properly.
I am making an android app in which there is one List view. On selecting the particular item for first time, I have changed text color of that item. Multiple selection is allowed for List view. Now there is one text view named "Done". When user clicks on "Done", items which are not selected from List view should be removed. What should I do? Below is my code...
tvDone.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if( colorRow > 0 )
{
AlertDialog builder = new AlertDialog.Builder(NewFriendList.this).create();
builder.setTitle("Save to List");
builder.setMessage("Do You Want to Save?");
builder.setButton("Save", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
tvEdit.setVisibility(View.VISIBLE);
tvClear.setVisibility(View.VISIBLE);
tvDelete.setVisibility(View.VISIBLE);
}
});
builder.setButton2("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
chkText.setTextColor(Color.BLACK);
tvEdit.setVisibility(View.INVISIBLE);
tvClear.setVisibility(View.INVISIBLE);
tvDelete.setVisibility(View.INVISIBLE);
}
});
builder.show();
}
else
Toast.makeText(getBaseContext(), "Select Friends", 1000).show();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
checked = lvDialog.getCheckedItemPositions();
chkText = (CheckedTextView) arg1.findViewById(R.id.txt);
if(checked.get(arg2))
{
chkText.setTextColor(Color.CYAN);
colorRow ++;
}
else
{
chkText.setTextColor(Color.BLACK);
colorRow--;
}
}
});
The standard way to do such actions is to use Action mode of action bar.
Anyways, Here's an example:
DataModel: This exposes data manipulation methods to local code. Here its just using in-memory data structures, but in real applications, it can be backed by a database or a web service or something else.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class DataModel {
private static DataModel ourInstance = new DataModel();
private final List<String> mPersons;
private final HashMap<String,Set<String>> mGroups;
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
mPersons = new ArrayList<String>();
mGroups = new HashMap<String, Set<String>>();
for (int i = 0; i < 50; i++){
mPersons.add("person_"+i);
}
}
public void updateGroup(String oldName, String newName, Set<String> members){
assert newName != null && !newName.isEmpty() && members != null : "data must not be null or empty";
if(oldName != null){
mGroups.remove(oldName);
}
mGroups.put(newName, members);
}
public void deleteGroup(String name){
mGroups.remove(name);
}
public boolean isMember(String groupName, String memberName){
return mGroups.containsKey(groupName) && mGroups.get(groupName).contains(memberName);
}
public List<String> getGroups(){
List<String> groups = new ArrayList<String>();
for (String s : mGroups.keySet()){
groups.add(s);
}
return groups;
}
public List<String> getMembersOf(String groupName){
List<String> members = new ArrayList<String>();
if(mGroups.containsKey(groupName)){
members.addAll(mGroups.get(groupName));
}
return members;
}
public List<String> getPersons(){
List<String> persons = new ArrayList<String>();
persons.addAll(mPersons);
return persons;
}
}
Activity to List data: Allows action mode by long clicking any item, or edit an item by clicking on it.
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.List;
public class GroupActivity extends ListActivity implements AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener {
public static final int REQ_CODE_EDIT_GROUP = 101;
private List<String> mSelection;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSelection = new ArrayList<String>();
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1);
mAdapter.addAll(DataModel.getInstance().getGroups());
setListAdapter(mAdapter);
getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(this);
getListView().setOnItemClickListener(this);
}
private void refresh(){
mAdapter.clear();
mAdapter.addAll(DataModel.getInstance().getGroups());
mAdapter.notifyDataSetInvalidated();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add("New");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().equals("New")){
startEditor(null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void startEditor(String groupName){
Intent i = new Intent(this,EditorActivity.class);
if(groupName != null){
i.putExtra(EditorActivity.KEY_EDIT_GROUP,groupName);
}
startActivityForResult(i,REQ_CODE_EDIT_GROUP);
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean checked) {
if(checked){
mSelection.add(mAdapter.getItem(i));
}else {
mSelection.remove(mAdapter.getItem(i));
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuItem item = menu.add("Delete");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if(menuItem.getTitle().equals("Delete")){
for (String groupName : mSelection){
DataModel.getInstance().deleteGroup(groupName);
}
refresh();
actionMode.finish();
return true;
}else {
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
mSelection.clear();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE_EDIT_GROUP && resultCode == RESULT_OK){
refresh();
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String groupName = mAdapter.getItem(i);
startEditor(groupName);
}
}
Activity to edit data : Allows editing names and selections etc.
It has a Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Group name"
android:inputType="text"/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
And Activity code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import java.util.HashSet;
public class EditorActivity extends Activity {
public static final String KEY_EDIT_GROUP = "edit_group";
private EditText mNameEdit;
private ListView mListView;
private ArrayAdapter<String> mAdapter;
private String mOldGroupName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
mNameEdit = (EditText) findViewById(R.id.edit);
mListView = (ListView) findViewById(R.id.list);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1);
mAdapter.addAll(DataModel.getInstance().getPersons());
mListView.setAdapter(mAdapter);
mOldGroupName = getIntent().getStringExtra(KEY_EDIT_GROUP);
if(mOldGroupName != null){
mNameEdit.setText(mOldGroupName);
for (int i = 0 ; i < mAdapter.getCount(); i++){
DataModel dm = DataModel.getInstance();
String member = mAdapter.getItem(i);
if(dm.isMember(mOldGroupName,member)){
mListView.setItemChecked(i,true);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add("Done");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().equals("Done")){
String newGroupName = mNameEdit.getText().toString();
if(newGroupName == null || newGroupName.isEmpty()){
Toast.makeText(this,"Invalid group name",Toast.LENGTH_LONG).show();
return true;
}
HashSet<String> selectedMembers = new HashSet<String>();
for (int i = 0 ; i < mAdapter.getCount(); i++){
if(mListView.isItemChecked(i)){
selectedMembers.add(mAdapter.getItem(i));
}
}
DataModel.getInstance().updateGroup(mOldGroupName,newGroupName,selectedMembers);
setResult(RESULT_OK);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}