Refresh fragment from adapter - android

I have ListView with items in my fragment. Every item has counter for example
Item 1 - 4
Item 2 - 5
On the top of the fragment I have textView with sum of all elements : sum - 9. I can delete Item with click on image on the item row. In adapter (getView()) it goes like this :
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mParts.remove(part);
notifyDataSetChanged();
dialog.dismiss();
}
});
The item is being removed from list but counter doesn't change value - for example Item 2 was removed but counter still shows 5. I update it in onResume() method and it works but only if I leave fragment and come back to it. I try to write update method in fragment and use it in adapter - I created constructor with fragment :
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,InvFragment mFragment) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mFragment = mFragment;
}
but when I call fragment.something I get null point exception :/ How can I refresh fragment/counter textView from adapter ? I also tried to set fragment again but it doesn't work.
Part of my adapter (it's quite long)
public class PartAdapter extends ArrayAdapter {
private OnUpdateListener listener;
public interface OnUpdateListener {
void onUpdate(String text);
}
public void setOnUpdateListner(OnUpdateListener listener) {
this.listener = listener;
}
private List<Part>mParts;
private LayoutInflater mInflater;
private TextView mPartName;
public CheckBox mState;
private ImageView mActionArrow;
public static final String TAG = PartAdapter.class.getSimpleName();
private static final int CAM_REQUEST = 1313;
private InvActivity mActivity;
private AdapterCallback mAdapterCallback;
private TextView mCounter;
private ImageView mDelete;
private InvFragment mFragment;
public boolean shouldScan = true;
private final byte[] pal = new byte[]{
(byte) 0xDA, (byte) 0xAD, // const
(byte) 0x04, (byte) 0x74, (byte) 0x31, // com
(byte) 0xe7, (byte) 0x64 //last
};
private final byte[] readId = new byte[]{
(byte) 0xDA, (byte) 0xAD, // const
(byte) 0x04, (byte) 0x6f, (byte) 0x69, // com
(byte) 0xec, (byte) 0x6e //last
};
private UsbManager usbManager;
private UsbDevice device;
public List<String> codes;
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,AdapterCallback callback) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mAdapterCallback = callback;
}
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,InvFragment mFragment) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mFragment = mFragment;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView=mInflater.inflate(R.layout.part_item,parent,false);
mState = (CheckBox) convertView.findViewById(R.id.state_chb);
mDelete = (ImageView)convertView.findViewById(R.id.delete_car);
mDelete.setVisibility(View.INVISIBLE);
final Part party = mParts.get(position);
if(party.isScan() || party.getType().contentEquals("2")) {
mState.setChecked(true);
} else if (!party.isScan()){
mState.setChecked(false);
}
if(party.getType().contentEquals("2"))
mDelete.setVisibility(View.VISIBLE);
if(mParts.get(position).getClass().isInstance(new Part())) {
final Part part = (Part) mParts.get(position);
mPartName = (TextView)convertView.findViewById(R.id.car_name_tv);
mState = (CheckBox) convertView.findViewById(R.id.state_chb);
mPartName.setText(part.getName());
mActionArrow = (ImageView)convertView.findViewById(R.id.arrow_action);
mCounter = (TextView)convertView.findViewById(R.id.car_count_tv);
mCounter.setText(part.getQuantity());
if(!part.isScan()) {
mState.setChecked(false);
} else if(part.isScan() || part.getType().contentEquals("2")) {
mState.setChecked(true);
}
mActionArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_context_menu);
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int totalSum = 5;
int partValue = 2;
mParts.remove(part);
notifyDataSetChanged();
dialog.dismiss();
if(listener != null){
listener((totalSum - partValue).toString());
}
}
});
LinearLayout photo = (LinearLayout)dialog.findViewById(R.id.photo_layout);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.dispatchTakePictureIntent();
}
});
LinearLayout note = (LinearLayout)dialog.findViewById(R.id.note_layout);
note.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
final Dialog noteDialog = new Dialog(getContext());
noteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteDialog.setContentView(R.layout.dialog_note);
final EditText noteET = (EditText)noteDialog.findViewById(R.id.note_et);
if(!part.getNote().contentEquals("null"))
noteET.setText(part.getNote());
Button save = (Button)noteDialog.findViewById(R.id.save_button);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
part.setNote(noteET.getText().toString());
noteDialog.dismiss();
}
});
noteDialog.show();
Button cancel = (Button) noteDialog.findViewById(R.id.cancel_button);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
}
});
}
});
LinearLayout values = (LinearLayout)dialog.findViewById(R.id.values_layout);
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog noteDialog = new Dialog(getContext());
noteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteDialog.setContentView(R.layout.dialog_note);
final EditText noteET = (EditText)noteDialog.findViewById(R.id.note_et);
noteET.setInputType(InputType.TYPE_CLASS_NUMBER);
Button save = (Button)noteDialog.findViewById(R.id.save_button);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
part.setQuantity(noteET.getText().toString());
noteDialog.dismiss();
dialog.dismiss();
}
});
noteDialog.show();
Button cancel = (Button) noteDialog.findViewById(R.id.cancel_button);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
dialog.dismiss();
}
});
}
});
dialog.show();
}
});
}
return convertView;
}
and from my activity :
public void onUpdate(String value){
mCountTV.setText(value);
}
private void createAdapter() {
adapter.setOnUpdateListner(this);
}
}

You can follow a process like below.
In your PartAdapter set a listener which will implemented in Fragment used to update value of sum text view.
class PartAdapter {
private OnUpdateLitener listener;
public interface OnUpdateListener {
void onUpdate(String text);
}
public void setOnUpdateListner(OnUpdateListener listener) {
this.listener = listener;
}
// in your getView() method
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mParts.remove(part);
notifyDataSetChanged();
if(listener != null){
listener.onUpdate(String.valueOf(totalSum - partValue));
}
dialog.dismiss();
}
});
}
In your fragment
class MyFragment {
private OnUpdateListener listener;
void onAttach(Activity activity){
if(!(activity instaceof PartAdapter.OnUpdateListener)){
throw new IllegalStateException("Must implement OnUpdateListener");
}
listener = (PartAdapter.OnUpdateListener) activity;
}
private void createAdapter() {
PartAdapter adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity, new AdapterCallback() {
#Override
public void onMethodCallback() {
Log.e(TAG, "onMethodCallback: ");
}
});
adapter.setOnUpdateListener(this);
mPartsLV.setAdapter(adapter);
}
}
In your activity
class MainActivity implements PartAdapter.OnUpdateListener {
public void onUpdate(String value){
textView.setText(value);
}
}

Related

Hello, please tell me how to send ArrayList to another activity

I tried all the possible options that I just found.
I can’t send ArrayList to another activity via the Parcelable interface.
To implement a media player
String format information it sends.
I would be very grateful, maybe there are some other options. This is the first time I'm asking a question here
Here is my activity that I use to send, the code is still very raw
public class MainActivity extends AppCompatActivity {
ScheduledExecutorService scheduledExecutorService;
public MediaPlayer mediaPlayer;
private SeekBar seekBar;
private ImageView btn_Play;
private ImageView btn_Next;
private ImageView btn_Pre;
private TextView setCurrentDuration, setTotalDuration;
private ArrayList<SoundInfo> audioList = new ArrayList<>();
SoundAdapter adapter = new SoundAdapter();
public Handler handler = new Handler();
AudioEffect audioEffect;
private int currentPosition = 0;
private SoundInfo soundInfo = new SoundInfo(this);
SoundEffects soundEffects;
boolean mediaPauseStat = false;
Context context;
PageFragmentOne pageFragmentOne;
//public MainActivity(PageFragmentOne pageFragmentOne) {
// this.pageFragmentOne = pageFragmentOne;
//}
MediaManager mediaManager = new MediaManager(this, adapter, audioList);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Старт сервиса
//Intent i = new Intent(this, MediaPlaybackService.class);
//i.putExtra("play", "письмо от главного активити");
//startService(i);
//mediaManager.LoadSounds();
/**
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
////////////////////////////////////////////////////////////////////////////////////////////
setCurrentDuration = findViewById(R.id.current_Duration);
setTotalDuration = findViewById(R.id.total_Duration);
seekBar = findViewById(R.id.seekBar);
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(this));
// Оформление отображения адаптера
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.list_item_divider, null));
list.addItemDecoration(dividerItemDecoration);
///////////////////////////////////////////////
soundInfo.setMassive(audioList);
adapter.setOnItemClickListener(new SoundAdapter.OnItemClickListener() {
#Override
public void onClick(View v, final SoundInfo obj, final int position, final ImageView onNext) {
final SoundInfo path = audioList.get(position);
String audioPath = obj.getData();
prepareMedia(position);
// Задаем текующию позицию трека
currentPosition = position;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
// Всегда должен быть после старта плеера, что бы не вылазило 238
updateProgressBar();
//seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
btn_Play.setImageResource(R.drawable.btn_pause);
}
});
// Перемотка аудио
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Слишком часто обновляет
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(false);
soundInfo.setMediaRewind(false);
mediaPlayer.pause();
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mediaPlayer.seekTo(seekBar.getProgress());
return false;
}
});
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(true);
//soundInfo.setMediaRewind(true);
mediaPlayer.start();
}
}
});
// Кнопка проигрывания и паузы
btn_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mediaPlayer.isPlaying()) {
onPlay();
} else {
onPaused();
}
}
});
// Следующий трек
btn_Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onNext();
}
});
// Предыдущий трек
btn_Pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPre();
}
});
}
});
init();
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// String yourValue = b.getString("ser");
Bundle bundle = intent.getExtras();
}
}
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
//Intent i = new Intent(MainActivity.this, MediaPlaybackService.class);
//startService(i);
////////////////////////////////////////////////////////////////////////////////////////////
}
public void init() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Разрешение не предоставляется
// Должны ли мы показать объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Показать объяснение пользователю * асинхронно* -- не блокировать
// этот поток ждет ответа пользователя! После пользователя
// увидев объяснение, попробуйте еще раз запросить разрешение.
} else {
// Никаких объяснений не требуется; запросить разрешение
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO},
101);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS является
// app-определенная константа int. Метод обратного вызова получает
// результат запроса.
}
} else {
// Разрешение уже предоставлено
//loadSounds();
mediaManager.LoadSounds();
}
//bPlayPause = findViewById(R.id.bPlayPause);
//lv = (ListView) findViewById(R.id.lvPlayList);
btn_Play = findViewById(R.id.btn_Play);
btn_Next = findViewById(R.id.btn_Next);
btn_Pre = findViewById(R.id.btn_Pre);
}
Here is my SoundInfo
public class SoundInfo implements Parcelable {
private String data, artist, title;
private Context context;
private String pathData;
public SoundInfo(MainActivity context) {
this.context = context;
}
public SoundInfo() {
}
public SoundInfo(MainMediaPlayList context) {
this.context = context;
}
public SoundInfo(MediaPlaybackService mediaPlaybackService, String star) {
this.context = mediaPlaybackService;
this.star = star;
}
protected SoundInfo(Parcel in) {
data = in.readString();
artist = in.readString();
title = in.readString();
pathData = in.readString();
mediaPauseStat = in.readByte() != 0;
ismediaRewind = in.readByte() != 0;
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
star = in.readString();
}
public static final Creator<SoundInfo> CREATOR = new Creator<SoundInfo>() {
#Override
public SoundInfo createFromParcel(Parcel in) {
return new SoundInfo(in);
}
#Override
public SoundInfo[] newArray(int size) {
return new SoundInfo[size];
}
};
public void SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public String getData() {
return data;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public void setData(String artist) {
this.data = data;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setTitle(String title) {
this.title = title;
}
public void setpathData(String pathData) {
this.pathData = pathData;
}
public String getpathData() {
return pathData;
}
// Запись в память для отображения времени
boolean mediaPauseStat = true;
boolean ismediaRewind = true;
public void setMediaPauseStat(boolean mediaPauseStat) {
this.mediaPauseStat = mediaPauseStat;
}
public boolean getMediaPauseStat() {
return mediaPauseStat;
}
public void setMediaRewind(boolean isMediaRewind) {
this.ismediaRewind = ismediaRewind;
}
public boolean getMediaRewind() {
return ismediaRewind;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Массив
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
public ArrayList<SoundInfo> getMassive() {
return audioList;
}
public void setMassive(ArrayList<SoundInfo> audioList) {
this.audioList = audioList;
}
private String star;
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(artist);
dest.writeString(title);
dest.writeString(pathData);
dest.writeByte((byte) (mediaPauseStat ? 1 : 0));
dest.writeByte((byte) (ismediaRewind ? 1 : 0));
dest.writeTypedList(audioList);
dest.writeString(star);
}
}
Here is my adater which I use
public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.ViewHolder> {
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
Context context;
//private String[] items;
private OnItemClickListener onItemClickListener;
public void setItems(Context context, ArrayList<SoundInfo> audioList) {
this.context = context;
this.audioList = audioList;
//audioList.addAll(items);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_audio, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(audioList.get(position));
holder.clickFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SoundInfo path = audioList.get(position);
onItemClickListener.onClick(view, path, position, holder.onNext);
}
});
}
#Override
public int getItemCount() {
return audioList == null ? 0 : audioList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView data, title, artist;
private ImageView onNext;
private View clickFile;
ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.tvSoundTitle);
artist = view.findViewById(R.id.tvSoundArtist);
clickFile = view.findViewById(R.id.clickFile);
//data = view.findViewById(R.id.item_title);
//onNext = view.findViewById(R.id.imageNext);
}
public void bind(SoundInfo soundInfo) {
title.setText(soundInfo.getTitle());
artist.setText(soundInfo.getArtist());
//clickFile.setText(soundInfo.getData());
}
}
// Передача данных в основной активити
public interface OnItemClickListener {
void onClick(View view, SoundInfo obj, int position, ImageView onNext);
}
}
Here is the second activity that an ArrayList gets.
Bundle bundle = getIntent().getExtras();
ArrayList<SoundInfo> audioList = bundle.getParcelableArrayList("MEDIA_MASSIVE");
adapter.setItems(MainMediaPlayList.this, audioList);
adapter.notifyDataSetChanged();
// загрузка адаптера
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(MainMediaPlayList.this));
When you open a new activity, the application crashes
does not display any errors in the log, the problem is as I understand that intent can not find
audioList as it seems to me
If I remove the method everything loads
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
Here I took off the launch log, it may somehow help
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: get the overscroller config
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
2020-03-08 18:09:43.506 15730-15730/com.shimmer.myapplication D/ActivityThread: add activity client record, r= ActivityRecord{e3185e4 token=android.os.BinderProxy#837d3d7 {com.shimmer.myapplication/com.shimmer.myapplication.MainActivity}} token= android.os.BinderProxy#837d3d7
I don't think so, You can send an ArrayList like this.
I recommend you sending Class instead of sending an Arraylist.
So, just create a class like AudiolistHolder and put your ArrayList inside this class and don't forget to implement Parcelable interface for this class, too, and send this class between activities this should solve your problem. I always use this way.
EDIT:
You can use this to send your data
Intent intent2 = new Intent(this, MainMediaPlayList.class);
MassiveAudioList m = new MassiveAudioList(audioList);
intent2.putExtra("MEDIA_MASSIVE”, m);
startActivity(intent2);
and you can use this in your second activity to retrieve data
MassiveAudioList massiveAudio=getIntent().getParcelableExtra("MEDIA_MASSIVE");
ArrayList<SoundInfo> audioList = massiveAudio.getMassiveAudioList();
Have you tried like this with arraylist
I think it can be,
In MainActivity.java
ArrayList<String> audioList= new ArrayList<>();
audioList.add("ChipThrills");
Intent i = new Intent(MainActivity.this, Secondactivity.class);
i.putExtra("Musickey", audioList);
startActivity(i);
In SecondActivity.java
ArrayList<String> audioList = (ArrayList<String>) getIntent().getSerializableExtra("Musickey");
I am writing to you here because I did not understand how to add code to the comment
And how do I extract data by adding it to an array. If of course I did the right thing, I'm new to this field. Thanks.
public class MassiveAudioList implements Parcelable {
private ArrayList<SoundInfo> audioList = new ArrayList<>();
private Context context;
public MassiveAudioList(Context context) {
this.context = context;
}
public MassiveAudioList(ArrayList audioList) {
this.audioList = audioList;
}
protected MassiveAudioList(Parcel in) {
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
}
public static final Creator<MassiveAudioList> CREATOR = new Creator<MassiveAudioList>() {
#Override
public MassiveAudioList createFromParcel(Parcel in) {
return new MassiveAudioList(in);
}
#Override
public MassiveAudioList[] newArray(int size) {
return new MassiveAudioList[size];
}
};
public ArrayList<SoundInfo> getMassiveAudioList() {
return audioList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(audioList);
}
}
public void onMainMediaPlayList(View view) {
Log.d("TAG", "soundinfo" + soundInfo.getData());
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
massiveAudioList = new MassiveAudioList(this);
MassiveAudioList m = new MassiveAudioList(audioList);
Bundle bundle = new Bundle();
bundle.putParcelable("MEDIA_MASSIVE", m);
intent2.putExtras(bundle);
startActivity(intent2);
}

Unable to update view on data change in Epoxy Controller

I am using Epoxy Controller for Recycler View. I am having trouble changing the view after data changed by the user action.
Basically I have a switch button in a view which is used inside a recycler view and I am trying to update the view on switch button state change. I am calling requestModelBuild() in setProductList() function of the epoxy controller but change is not reflected in the view.
public class SellerInventoryListEpoxyController extends EpoxyController {
private List<Product> productList = Collections.emptyList();
private Context context;
private SellerInventoryListEpoxyController.Callbacks callbacks;
public void setProductList(List<Product> productList, Context context, SellerInventoryListEpoxyController.Callbacks callbacks) {
this.productList = productList;
this.context = context;
this.callbacks = callbacks;
requestModelBuild();
}
#Override
protected void buildModels() {
for (int i = 0; i < productList.size(); i++) {
new InventoryProductDetailModel_()
.id(productList.get(i).getId())
.product(productList.get(i))
.position(i)
.listSize(productList.size())
.callbacks(callbacks)
.context(context)
.addTo(this);
}
}
public interface Callbacks {
void onViewComboClick(Product productComboList);
void onProductListingStatusChanged(Boolean newStatus, int productSellerId);
void onRecyclerViewReachEnd();
}
}
public class InventoryProductDetailModel extends EpoxyModelWithHolder<InventoryProductDetailModel.ViewHolder> implements CompoundButton.OnCheckedChangeListener {
#EpoxyAttribute
Product product;
#EpoxyAttribute
int position;
#EpoxyAttribute
int listSize;
#EpoxyAttribute
Context context;
#EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
SellerInventoryListEpoxyController.Callbacks callbacks;
#Override
protected ViewHolder createNewHolder() {
return new ViewHolder();
}
#Override
protected int getDefaultLayout() {
return R.layout.inventroy_item_layout;
}
private DrawableCrossFadeFactory factory =
new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
#Override
public void bind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.bind(holder);
holder.quantity.setText(String.format("Available :%d", product.getTotalStock()));
holder.brand.setText(product.getProduct().getBrandName());
holder.title.setText(product.getProduct().getTitle());
holder.category.setText(product.getProduct().getCategoryName());
holder.sku.setText(String.format("Sku: %s", product.getSku()));
holder.inventoryItemConstrainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("product_id", product.getId());
context.startActivity(intent);
}
});
if (product.getProductCombos() != null && product.getProductCombos().size() > 0) {
holder.variationCount.setVisibility(View.GONE);
holder.comboBtn.setVisibility(View.VISIBLE);
holder.comboBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callbacks.onViewComboClick(product);
}
});
}
if (product.getSellerActive()) {
holder.productStatusSwitch.setText("Active");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(true);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(context.getResources().getColor(R.color.colorAccent));
} else {
holder.productStatusSwitch.setText("Inactive");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(false);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(Color.parseColor("#ff0000"));
}
holder.variationCount.setText(format("Variation(%d)", product.getVariantCount()));
holder.variationCount.setVisibility(View.VISIBLE);
holder.comboBtn.setVisibility(View.GONE);
loadImage(holder.productImage, Utils.getRequiredUrlForThisImage(holder.productImage, product.getProduct().getImage()));
if (position == listSize - 2) {
callbacks.onRecyclerViewReachEnd();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callbacks.onProductListingStatusChanged(isChecked, product.getId());
}
private void loadImage(ImageView imageView, String url) {
Glide.with(imageView.getContext()).asBitmap()
.load(Utils.getRequiredUrlForThisImage(imageView, url))
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.fitCenter())
.transition(withCrossFade(factory))
.placeholder(R.mipmap.product)
.into(imageView);
}
#Override
public void unbind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.unbind(holder);
}
public static class ViewHolder extends EpoxyHolder {
TextView quantity, brand, title, category, variationCount, comboBtn;
ImageView productImage, btn_product_detail;
ProgressBar progressBar;
ConstraintLayout inventoryItemConstrainLayout;
private TextView sku;
private Switch productStatusSwitch;
#Override
protected void bindView(#NonNull View itemView) {
productStatusSwitch = itemView.findViewById(R.id.productStatusSwitch);
quantity = itemView.findViewById(R.id.product_qty);
brand = itemView.findViewById(R.id.product_brand);
title = itemView.findViewById(R.id.product_title);
sku = itemView.findViewById(R.id.sku);
category = itemView.findViewById(R.id.product_category);
variationCount = itemView.findViewById(R.id.variantCount);
productImage = itemView.findViewById(R.id.product_image);
btn_product_detail = itemView.findViewById(R.id.btn_product_detail);
inventoryItemConstrainLayout = itemView.findViewById(R.id.inventory_item_constrain_layout);
comboBtn = itemView.findViewById(R.id.combo_btn);
progressBar = itemView.findViewById(R.id.progressbar);
progressBar.setVisibility(View.GONE);
}
}
#Override
public int hashCode() {
super.hashCode();
return product.hashCode();
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
private void addProductListingChangeObserver(final Boolean newStatus, final int productSellerId) {
ProductUpdate productUpdate = new ProductUpdate();
productUpdate.setSellerActive(newStatus);
mInventoryViewModel.updateProductSeller(productSellerId, productUpdate).observe(this, new Observer<Resource<ProductSeller>>() {
#Override
public void onChanged(Resource<ProductSeller> productSellerResource) {
if (productSellerResource.status == Status.ERROR) {
progressBar.setVisibility(View.GONE);
} else if (productSellerResource.status == Status.SUCCESS) {
progressBar.setVisibility(View.GONE);
if (productSellerResource.data != null && productSellerResource.data.isSellerActive() == newStatus) {
for (int i = 0; i < productList.size(); i++) {
if (productList.get(i).getId() == productSellerId) {
productList.get(i).setSellerActive(newStatus);
break;
}
}
sellerInventoryListEpoxyController.setProductList(productList, getContext(), InventoryFragment.this);
}
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
}
In addProductListingChangeObserver() function one object of productList is modified and new productList is passed to the EpoxyController and requestModelbuild is called but the view is not modifying as expected.

RecyclerView filled with Objects from SharedPreferences is slow and laggy

I am building an app which has a RecyclerView which holds Objects that are retrieved from SharedPreferences.
Unfortunately the RecyclerView is lagging when it is binded.
This is my Adapter
public class ShiftAdapter extends RecyclerView.Adapter<ShiftAdapter.ViewHolder>{
private List<Shift> mDataSet;
private Context mContext;
private static final String TAG = "ShiftAdapter";
public int previousExpandedPosition = -1;
public int mExpandedPosition = -1;
private static SharedPreferences mPrefs;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Boolean isStart;
private Date shiftIn;
private Date shiftOut;
private Date mDate;
public EditText mshiftInText;
public EditText mshiftOutText;
public Date date;
public ShiftAdapter(Context context, List<Shift> list) {
mDataSet = list;
mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mDate;
public TextView mTime;
public TextView mPay;
public RelativeLayout mRelativeLayout;
public LinearLayout mExepandableLayout;
public Date mshiftIn;
public Date mshiftOut;
public EditText mshiftInText;
public EditText mshiftOutText;
public Button mUpdateButton;
public Button mDeleteButton;
public ViewHolder(View v) {
super(v);
mDate = (TextView) v.findViewById(R.id.date_TV);
mTime = (TextView) v.findViewById(R.id.time_TV);
mPay = (TextView) v.findViewById(R.id.pay_TV);
mRelativeLayout = (RelativeLayout) v.findViewById(R.id.rel_layout);
mExepandableLayout = (LinearLayout) v.findViewById(R.id.expandableLayout);
mshiftInText = (EditText) v.findViewById(R.id.setShiftIn);
mshiftOutText = (EditText) v.findViewById(R.id.setShiftOut);
mUpdateButton = (Button) v.findViewById(R.id.updateButton);
mDeleteButton = (Button) v.findViewById(R.id.deleteButton);
}
}
#Override
public ShiftAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.shift, parent, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
//TODO:Bind all the view elements to Shift Properties
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
// Format double
String hours = new DecimalFormat("##.##").format(mDataSet.get(i).getHours());
String pay = new DecimalFormat("##.##").format(mDataSet.get(i).getPay());
//set the Text
holder.mTime.setText(hours);
holder.mDate.setText(mDataSet.get(i).dateToString());
holder.mPay.setText(pay);
Log.d(TAG, "onBindViewHolder: called");
// new AsyncTask<>().ex
//Expand mExapndableLayout
final int position = i;
final boolean isExpanded = position ==mExpandedPosition;
holder.mExepandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
// //set shift Times
// shiftIn = mDataSet.get(position).getInDate();
// shiftOut = mDataSet.get(position).getInDate();
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
//fill expandable layout
holder.mshiftInText.setText(mDataSet.get(position).fullTimeToString(0));
final EditText in = holder.mshiftInText;
final EditText out = holder.mshiftOutText;
//edit mShiftIn Text
holder.mshiftInText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =true;
timePickerDialog(in,out);
}
});
holder.mshiftOutText.setText(mDataSet.get(position).fullTimeToString(1));
//edit MshiftOut Text
holder.mshiftOutText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =false;
timePickerDialog(in,out);
}
});
//updateButton onClick
holder.mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
shiftIn = mDataSet.get(position).getInDate();
shiftOut = mDataSet.get(position).getOutDate();
if(Validate.getValidate().isDateValid(shiftIn,shiftOut)) {
SharedPrefs.getInstance(mContext).editShift(newShift(shiftIn, shiftOut),Integer.toString(position));
int length = SharedPrefs.getInstance(mContext).getLength() - 1;
if (SharedPrefs.getInstance(mContext).getShift(length) != null) {
Log.d(TAG, "Edit Shift onClick: Success");
SharedPrefs.getInstance(mContext).saveShiftList(SharedPrefs.getInstance(mContext).sortList(SharedPrefs.getInstance(mContext).getShiftList()));
ShiftsFragment.updateUI();
Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
}
} else {
mShiftOut.setBackgroundResource(R.drawable.red_border);
Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show(); }
} catch(Exception e){
Log.d(TAG, "onDateSelected: "+e.toString());
Toast.makeText(mContext,"update FAIL", Toast.LENGTH_SHORT).show();
}
// update the Shift
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
areYouSure(mExpandedPosition);
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public Date timePickerDialog(EditText in,EditText out) {
mshiftInText = in;
mshiftOutText = out;
new SingleDateAndTimePickerDialog.Builder(mContext)
.title(mContext.getResources().getString(R.string.choose_time))
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {
if(!isStart) {
date = mDate;
}
}
}).defaultDate(returnDate(date))
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
mDate = date;
if (isStart) {
updateShiftIn(mDate);
mshiftInText.setText(dateToString(mDate));
} else {
updateShiftOut(mDate);
mshiftOutText.setText(dateToString(mDate));
}
}
}).display();
return mDate;
}
public String dateToString(Date date)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String string = df.format(date);
return string;
}
private void updateShiftIn(Date date) {
shiftIn = date;
}
private void updateShiftOut(Date date) {
shiftOut = date;
}
private Date returnDate(Date date)
{
if(date!=null)
{
return date;
}
else return mDate;
}
private void areYouSure(int i)
{
final String position = Integer.toString(i);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "onClick: isSure=true;");
SharedPrefs.getInstance(mContext).removeShift(position);
ShiftsFragment.updateUI();
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "onClick: isSure= false");
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(mContext.getResources().getString(R.string.are_you_sure)).setPositiveButton(mContext.getResources().getString(R.string.confirm), dialogClickListener)
.setNegativeButton(mContext.getResources().getString(R.string.cancel), dialogClickListener).show();
}
private Shift newShift(Date start,Date stop)
{
int id = SharedPrefs.getInstance(mContext).getLength();
Shift shift = new Shift(dateToCalendar(start),dateToCalendar(stop),id);
return shift;
}
and this is the Fragment that has the RecyclerView
public class ShiftsFragment extends Fragment {
private Toolbar mToolbar;
private TimePicker timePicker1;
private List<Shift> shiftList = new ArrayList<>();
private RecyclerView recyclerView;
private RelativeLayout relativeLayout;
private RecyclerView.LayoutManager layoutManager;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Context mContext;
private ShiftAdapter mAdapter;
private MenuItem mAdd;
private Menu optionsMenu;
private LinearLayout mShiftAddLL;
private SharedPreferences mPrefs;
private static FragmentManager mFragmentManager;
private static final String TAG = "ShiftsFragment";
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG,"Clicked");
final View view = inflater.inflate(R.layout.shifts_layout,container,false);
mToolbar = view.findViewById(R.id.topbar);
mToolbar.inflateMenu(R.menu.toolbarmenu);
mShiftAddLL = view.findViewById(R.id.add_shiftLayout);
mAdd = mToolbar.getMenu().getItem(0);
timePicker1 = (TimePicker) view.findViewById(R.id.timePicker);
mFragmentManager = getFragmentManager();
//TODO:Add a summary bar on the bottom.
//get the context
mContext = getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.shift_list);
// Define a layout for RecyclerView
layoutManager = new GridLayoutManager(mContext,1);
recyclerView.setLayoutManager(layoutManager);
// Initialize a new Shift array
List<Shift> shiftList = initShifts();
Log.d(TAG,"shift array initiated");
// Initialize an array list from array
// Initialize a new instance of RecyclerView Adapter instance
mAdapter = new ShiftAdapter(mContext,shiftList);
// Set the adapter for RecyclerView
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
//Menu add button onClick
//Opens Add_Shift_Fragment
mAdd.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Fragment selectedFragment = new Add_Shift_Fragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return false;
}
});
return view;
}
//Initializes the Shift list from SharedPreferences and returns it.
private List<Shift> initShifts() {
return SharedPrefs.getInstance(mContext).getShiftList();
}
public static void updateUI()
{
Fragment selectedFragment = new ShiftsFragment();
mFragmentManager.beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
}
Everytime i launch the ShiftsFragment there are some frame skips, and the scrolling is choppy and laggy.
Maybe my SharedPreferences handling is what is slowing things down?
public class SharedPrefs {
private static SharedPrefs mSharedPrefs;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
protected Context mContext;
public static final String ID = "shiftList";
private SharedPrefs(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(ID, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
}
public static SharedPrefs getInstance(Context context) {
if (mSharedPrefs == null) {
mSharedPrefs = new SharedPrefs(context.getApplicationContext());
}
return mSharedPrefs;
}
public void saveShiftList(List<Shift> shiftList) {
Gson gson = new Gson();
String json = gson.toJson(shiftList);
mPrefsEditor.putString(ID, json);
mPrefsEditor.apply();
}
public void addShift (Shift shift)
{
List<Shift> shiftList= getShiftList();
shiftList.add(shift);
saveShiftList(shiftList);
}
//Replaced the shift#id with shift
public void editShift(Shift shift,String id)
{
removeShift(id);
addShift(shift);
}
public void removeShift(String id) {
List<Shift> shiftList = getShiftList();
int pos = Integer.parseInt(id);
shiftList.remove(pos);
saveShiftList(shiftList);
}
public void removeShift(int id) {
List<Shift> shiftList = getShiftList();
shiftList.remove(id);
saveShiftList(shiftList);
}
public Shift getShift(int id) {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
Shift shift = shiftList.get(id);
return shift;
}
public List<Shift> getShiftList() {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
if (shiftList!=null) {
return shiftList;
} else{
shiftList = new ArrayList<>();
return shiftList;
}
}
public List<Shift> sortList(List<Shift> shiftList)
{
Collections.sort(shiftList, new Comparator<Shift>() {
public int compare(Shift shift1, Shift shift2) {
if (shift1.getShiftStart() == null || shift2.getShiftStart() == null)
return 0;
return shift1.getShiftStart().compareTo(shift2.getShiftStart());
}
});
return shiftList;
}
public int getLength()
{
return getShiftList().size();
}
}
I have only found this problem with image loading, not just Strings from Object from SharedPrefs.

List refreshed withous notifyDataSetChange?

I have a little question for you. I have an app which displays a list of subjects which could be removed or addedd. During developing I realized that I could add new subject without call notifyDataSetChange, why?
Class (ListSubject) which manage list of subjects:
public static ListView mListView;
private Context mContext;
List<Subject> data;
SubjectAdapter subjectSubjectAdapter;
public ListSubject(Context mContext) {
this.mContext = mContext;
}
public List<Subject> populateList() {
DBManager db = new DBManager(mContext);
data = db.GetSubjects();
return data;
}
public void DeleteAll(){
DBManager db = new DBManager(mContext);
db.ClearTable("TBLSUBJECTS");
data.clear();
}
public void AddSubject(String name, int frequency){
DBManager db = new DBManager(mContext);
Subject subToAdd = db.InsertSubject(name, frequency);
data.add(subToAdd);
}
public void DeleteSubject(int id){
DBManager db = new DBManager(mContext);
db.DeleteSubject(id);
}
}
Class (ListSubjectActivity) which rappresents the activity where is listview:
DBManager db;
Button btnClearSubjectTable;
Button btnAddSub;
Context mContext;
private List<Subject> mListSubject;
private SubjectAdapter subjectAdapter;
private ListView lvSubject;
private ListSubject ls;
public ListSubjectActivity(Context mContext) {
this.mContext = mContext;
}
public ListSubjectActivity(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_subject);
db = new DBManager(this);
btnClearSubjectTable = (Button) findViewById(R.id.btnClearSubjectTable);
btnAddSub = (Button) findViewById(R.id.btnAddSubject);
lvSubject = (ListView)findViewById(R.id.subjectList);
mListSubject = new ArrayList<>();
ls = new ListSubject(getApplicationContext());
mListSubject = ls.populateList();
btnClearSubjectTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteAll();
subjectAdapter.notifyDataSetChanged();
}
});
btnAddSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(ListSubjectActivity.this);
dialog.setContentView(R.layout.dialog_insert_subject);
final EditText txtNewSubName = (EditText) dialog.findViewById(R.id.txtNewSubName);
final EditText txtFreqNewSub = (EditText) dialog.findViewById(R.id.txtFreqNewSub);
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.btnCancel);
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, 700);
}
});
subjectAdapter = new SubjectAdapter(getApplicationContext(), mListSubject);
lvSubject.setAdapter(subjectAdapter);
}
public void AddSubject(String newSub, int frequency)
{
ls.AddSubject(newSub, frequency);
}
My subject adapter:
private Context mContext;
private List<Subject> mList;
private ListSubject ls;
public SubjectAdapter(Context mContext, List<Subject> mList) {
this.mContext = mContext;
this.mList = mList;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_subject_list,null);
TextView txtSubjectName = v.findViewById(R.id.txtName);
TextView txtFrequency = v.findViewById(R.id.txtFrequency);
txtSubjectName.setText(mList.get(position).GetSubjectName());
txtFrequency.setText(Integer.toString(mList.get(position).GetFrequency()));
ls = new ListSubject(mContext);
ImageButton btnDeleteSub = (ImageButton) v.findViewById(R.id.btnDeleteSub);
btnDeleteSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteSubject(mList.get(position).GetSubjectID());
mList.remove(position);
notifyDataSetChanged(); useless
}
});
return v;
}
}
Keep in mind please, that I'm new in android development so could be make a lot of mistake. Thank you who help me
If your current code is what you're wondering about, you are calling notifyDataSetChanged() when adding an item. It's right here:
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged(); //see?
dialog.dismiss();
}
});

RecyclerView notifyDatasetChanged not working

I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.

Categories

Resources